megclaypool
4/27/2018 - 7:15 PM

Using jQuery code snippets in WordPress

Using jQuery code snippets in WordPress

I was trying to get the fitVids.js to work on a WP site, and couldn't get it! I'd copied and pasted their example code, switched out my own selectors, and nothing!!! I kept trying different selectors, messed around a bit with the code, no dice. Finally checked the terminal and saw that I had an error.

TypeError: $ is not a function when calling jQuery function

I have a simple jQuery script in a WordPress plugin that is using a jQuery wrapper like this:

$(document).ready(function(){

    // jQuery code is in here

});

I am calling this script from within the WordPress Dashboard and am loading it AFTER the jQuery framework has loaded.

When I check the page in Firebug I constantly keep receiving the error message:

TypeError: $ is not a function

$(document).ready(function(){

Should I maybe wrap the script in this function:

(function($){

    // jQuery code is in here

})(jQuery);

I have had this error quite a few times and am not sure how to handle it.

Any help would be greatly appreciated.

Matthew Blancarte replies:

This should fix it:

jQuery(document).ready(function($){
  //you can now use $ as your jQuery object.
  var body = $( 'body' );
});

Put simply, WordPress runs their own scripting before you can and they release the $ var so it won't collide with other libraries. This makes total sense, as WordPress is used for all kinds of web sites, apps, and of course, blogs.

From their documentation:

The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link.

In the noConflict() mode, the global $ shortcut for jQuery is not available...