Menu Close

How to Use jQuery in WordPress

jquery wordpress

Have you ever tried using jQuery in WordPress and couldn’t find out why it wasn’t working?

The reason behind this is simple and is probably not working because your code looks something like this example below:-

$(document).ready(function(){
  $("p").click(function(){
    $(this).hide();
  });
}); 

So why does this not work?

The reason is that in the console area when you view the code inspector, no doubt you will have an error that says something along the lines of jQuery cannot be defined. There are different ways to fix this, the ‘best’ way of fixing this is by editing the ‘enqueue’ setting which is usually within your functions.php file:-

wp_enqueue_script("jquery"); 

The code above is typically the default setting for WordPress Themes. This means that the usual ‘$’ shortcut for jQuery doesn’t work.

Most of the developers of plugins and theme developers are already aware of this, and they use ‘jQuery’ as opposed to ‘$’ to be safe and to ensure the plugin will be compatible.

/**** Typical jQuery ***/
$("#foo").doSomething();

/*** "Safe" method of jQuery in WordPress ***/
jQuery("#foo").doSomething(); 

The most frustrating thing about using ‘jQuery’ as opposed to ‘$’ everywhere within your WordPress files is that it doesn’t look as clean which makes it harder to read and that it bloats the size of your website.

If the script is being loaded in the footer (which you should be doing in the vast majority of cases) you can wrap the code in an anonymous function where you pass in jQuery to be mapped to $ as follows:-

(function($) {
	
	// $ Works! You can test it with next line if you like
	// console.log($);
	
})( jQuery ); 

If you really need to load the scripts in the header, you will probably need to use a document ready function anyway, so you can just pass in $ as follows:-

jQuery(document).ready(function( $ ) {
	
	// $ Works! You can test it with next line if you like
	// console.log($);
	
}); 

I hope this article has helped you to solve the problem. 

Posted in jQuery, WordPress

You can also read...