WordPress & jQuery: Fix JavaScript error “$ is not a function”


When using jQuery in WordPress you might be surprised by a

$ is not a function

JavaScript error.

For example, in a default WordPress 3.3.1 installation, the following JavaScript code leads to this error:

$(document).ready(function() {
  console.log($("body"));
});

The reason is, that WordPress by default uses jQuery’s “no conflict mode” to avoid compatibility problems with other JavaScript libraries that might could also use the $ variable. In detail, the jQuery script source included in WordPress activates this mode by calling jQuery.noConflict() (for WordPress 3.3.1 see line 5 in http://core.trac.wordpress.org/browser/tags/3.3.1/wp-includes/js/jquery/jquery.js#L5).

To fix the error replace jQuery’s $ shortcut by jQuery. Optionally, you can add a $ parameter your handler functions to define the $ shortcut inside the functions:

jQuery(document).ready(function($) {
  console.log($("body"));
});
,

3 responses to “WordPress & jQuery: Fix JavaScript error “$ is not a function””

  1. Thanks for this. I had encountered this issue a few times before (and worked out how to avoid it) but it’s useful to know why it happens.

  2. In WordPress IIS I currently have a broken NivoSlider with Firefox error:
    Error: TypeError: jQuery(…).nivoSlider is not a function
    Source File: http://localhost/wordpress/
    Line: 206
    afterLoad: function(){} // Triggers when slider has loaded

    This related to your post? Do you know a fix for this? Thanks 🙂

  3. Hi Richard,
    thanks for your comment. IMHO, your problem is not related to this post.
    I think you get this error because you don’t have the NivoSlider JavaScript files included in your page.
    Hope this helps…

Leave a Reply

Your email address will not be published. Required fields are marked *