How many times do you see awesome jQuery stuff that would be great on your blog or next website build?
It happens to me all the time. Plugins are great, but the jQuery jocks really know how to lay down some sweet stuff.
Early on in my WordPress days, I would admire jQuery, but never thought about using it, since it was “code” and seemed too difficult. After all, I would have to do something “special” to run jQuery on my WordPress site, right?
Wrong.
Here’s a nifty tip for those of you who never thought about running jQuery on your WordPress site, and a tip that might come in handy for those of you coding jQuery the “long” way.
jQuery is Baked In
First, let me address jQuery in WordPress.
As of WordPress 3.2.1, WordPress still ships with jQuery.
How great is that! If you were a little nervous about trying jQuery junk, worry no more! WordPress already has it baked in.
Now, how do you call on it for your plugins and themes?
The Shortcut
To start, you’ll probably enqueue it in your functions.php.
[cc lang=”php”]wp_enqueue_script(“jquery”);[/cc]
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.
Some of you may be using ‘jQuery’ all of the time instead of ‘$’ to be on the safe side. Unfortunately, this also has a down side.
[cc lang=”php”]/* Normal jQuery you see everywhere */
$(“#some-element”).blahBlahBlah();
/* “Safe” jQuery you see in WordPress */
jQuery(“#some-element”).blahBlahBlah();[/cc]
This will lead to code that is hard to read and bloated. Two pitfalls you want to avoid. Here’s the fix for scripts loading in your footer:
[cc lang=”php”](function($) {
// $ Works! You can test it with next line if you like
// console.log($);
})( jQuery );[/cc]
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.
[cc lang=”php”]jQuery(document).ready(function( $ ) {
// $ Works! You can test it with next line if you like
// console.log($);
});[/cc]
Now you’re all set!
If you haven’t implemented jQuery in your WordPress before, now you can do it with style!
Here’s a great tutorial on adding Dynamic jQuery Accordion Content in WordPress to get your feet wet.
[via Digging Into WordPress]
Speak your mind...