Friday, June 22, 2012

Including jQuery in WordPress (The Right Way)

If you want, you can just download jQuery, put it on your server and link to it from your header.php file in the section. But that can cause you grief. For one thing, some plugins use the jQuery library, and they are going to load it as well. This can cause problems. How was your plugin to know you already had it loaded?
Another thing is that WordPress already includes a copy of jQuery. Here is how you can load up jQuery in your theme the smart (and intended) way. Put the following code in your header.php file in the section:
 




Your theme probably already has the wp_head function, so just make sure you call the wp_enqueue_script function BEFORE that. Now you are all set to call your own jQuery JavaScript file, AFTER the wp_head function.


You are ready to rock, but there are still some considerations. For example, safeguarding yourself from the future possibility of conflict with other libraries. You really shouldn’t be using multiple JS libraries to begin with, but… better safe than sorry.
To be super-safe, you can put jQuery into “no conflict” mode and use a different shortcut for jQuery. In this case “$j” instead of the default “$”. The standard “$”, for example, can conflict with Prototype. Here is an example of a safe bit of jQuery JavaScript:
 
var $j = jQuery.noConflict();

$j(function(){

    $j("#sidebar li a").hover(function(){
     $j(this).stop().animate({
      paddingLeft: "20px&"
     }, 400);
    }, function() {
     $j(this).stop().animate({
      paddingLeft: 0
     }, 400);
    });

});
 
Can you recognize this bit of code? We use it right here on Modern WordPress to do the cool “link nudging” in the sidebar!

0 comments:

Post a Comment

I am a student of MS(CS), and also a computer software engineer and web developer.