jQuery Document Ready Function For WordPress

You can set up a jQuery document ready function for use with WordPress and use the jQuery library that WordPress ships with rather than use another one. Here are three ways to use jQuery document ready function with WordPress.

Usually, a jQuery document ready function is expressed as below.

$(document).ready(function(){


});

jQuery document ready 1st way

WordPress loads its own jQuery library in what is known as ‘no conflict mode‘ and the $ selector or variable that defines jQuery doesn’t work with the WordPress loaded jQuery version, so it has to be expressed more like so…

jQuery(document).ready(function($){

// Code goes here


});

Here we are using jQuery at the beginning of the document ready function and then passing or binding that to the $ selector, so now anywhere else in the code you can use the $ selector.

 

jQuery document ready 2nd way

There is also a shorthand version of the jQuery document ready function.

jQuery(function($) {

// Code goes here

});

Same issue here, using the jQuery at the beginning.

jQuery document ready 3rd way

Another way is to add the document ready code is inside a Javascript function …

(function($){

    $(function() {

	// Code goes here
		
    });

})(jQuery);

The outer Javascript function is known as an anonymous function and jQuery is wrapped at the end, so is therefore aliased or bound to the $ selector, so in the inner function the jQuery shorthand document does not need to be aliased.

Add the Javascript where needed or register and enqueue the script for usage.

1 Comment

  1. Avanti on October 20, 2018 at 8:42 am

    Thanks for the reminder and complete summary!

Leave a Comment