More jQuery for your Dollar ($); How to Write it the WordPress Way

7 Jun 2020 (Updated 13 Aug 2020)Tags: , ,

Disclaimer; I didn’t use jQuery at all for the theme I created for this site, so in most cases I believe the right way to write jQuery is to write none at all if you can help it (sticking to vanilla JavaScript instead).

However, there’s been many times where jQuery was just the quickest way to achieve something (particularly where ajax is concerned) and a lot of the time jQuery will be loaded by your site anyway; even if your own scripts don’t declare it as a dependency, a lot of commonly-installed plugins will.

So what’s the right way to write it? Well, with WordPress, you can’t simply jump in and get jiggie with jQuery the usual way – your dollar won’t get very far! This is because WordPress loads jQuery in compatibility mode, so you can’t use the $ sign without first ‘mapping’ it to jQuery (this is because other libraries being loaded may also be using the $ sign).

So, below are your options. I always go for the first one, because it seems clearer to me, but both will get the job done.


/**
 * The first way (recommended, for simplicity).
 */
jQuery(document).ready(function($) {
	
	// Your code here
	
});

/**
 * The second way (if you're a fan of immediately-invoked
 * anonymous functions.
 */
(function($) {
	
	// Your code here
	
})(jQuery);

Now go get your dollar’s worth! 🙂

Leave a Reply

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