DiggingIntoWordPress

by Chris Coyier & Jeff Starr

Using ‘$’ instead of ‘jQuery’ in WordPress

Posted by on

WordPress ships with jQuery (for longevity’s sake, as I write this WordPress is v3.2.1). To use jQuery in your plugins and themes “The Right Way” all you need to do is enqueue it (probably in your functions.php file):

wp_enqueue_script("jquery");

The tricky thing is this particular copy of jQuery is in compatibility mode by default. That means that the typical ‘$’ shortcut for jQuery doesn’t work, so it doesn’t conflict with any other JavaScript libraries that use the dollar sign also, like MooTools or Prototype.

Many plugin authors and theme developers are aware of this, and they use ‘jQuery’ instead of ‘$’ to be safe.

/* Normal jQuery you see everywhere */
$("#some-element").yaddaYaddaYadda();

/* "Safe" jQuery you see in WordPress */
jQuery("#some-element").yaddaYaddaYadda();

Here’s the thing… writing out ‘jQuery’ a billion times in a script makes it harder to read and bloats its size. Let’s stop doing that.

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 (technically any IIFE) where you pass in jQuery to be mapped to $.

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

If you absolutely need to load the scripts in the header, you’ll probably need to use a document ready function anyway, so you can just pass in $ there.

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

Go forth and write nice looking jQuery!

9 Responses

  1. Nice read, I just passed this onto a colleague who was doing some research on that. And he just bought me lunch since I found it for him smile So let me rephrase that: Thank you for lunch!

  2. I usually use this:

    $j=jQuery.noConflict();

  3. Just as a side note:
    I need to have the Q capitalized for the enqueue to work, don’t know why…
    wp_enqueue_script("jQuery");

  4. Yeah, using .noConflict () is actually more useful if you have some sort of library (with other functions, plugins, etc.) you need to load anytime, so you pretty much write it once and forget about it.

  5. awesome! This actually helped me out with a non-Wordpress related issue I have been having! now it’s all working well! :)
    Thanks

  6. Thank you, thank you, thank you. I’ve wondered how to do that.

  7. Brilliant, thanks for setting the record straight. I’ll make sure to pass this along!

  8. Thanks!!!

    I could not figure out why it was this way!!! I am so glad you cleared this up..

  9. It does bloat the size. I shall go forth and write nice looking JQuery thanks to your guidance.
    Sit vis nobiscum
    Winston

Comments are closed. Contact us with any critical information. Thank you!

Code is poetry