Troubleshooting jQuery in WordPress Themes

Here’s another “oh yeah, I always forget about that” geek item.

I spent a few hours today going nuts trying to figure out why the jQuery Cycle plug-in wasn’t working in a new theme I’m working on. The code ran great outside of WordPress, but the minute I placed it inside the theme, it broke.

Then I realized: when using jQuery in WordPress you always have to remember to explicitly call it by name rather than use the handy-dandy $(“#identifier”) short-cut that every example and demo online uses. The long-winded reasoning (as I discovered thanks to Techxplorer’s blog entry) is that the bundled version of jQuery built into WordPress since version 2.2 is initialized with jQuery.noConflict. The upside is that this keeps the jQuery library from crashing into other bundled libraries (like Prototype). The bad news is that it breaks support for the $ shortcut.

I came across an simple solution via Chris Mellon:

Instead, for interoperability, be sure to use jQuery() instead, which should accomplish the same thing.

A bad example:

var username = $('#username').val();

If Prototype were to be loaded on the page this snippet of JS is running on, it would throw an error, since it uses a different pattern for selecting DOM elements.

A good example:

var username = jQuery('#username').val();

This line should work on any page, regardless of library conflicts. It’s a couple extra characters to type, but in the end it’s really for the best – you get portability, and it’s more self-explanatory which library is being used when you go back to look at this code in 6 months.

You may also like...

Leave a Reply

%d bloggers like this: