When I was building this website, I wanted to add some simple hover effects, or image rollovers, to the home page of my site to enhance the look and feel of some of my buttons. I decided to use the jQuery JavaScript library to accomplish this. Now I have used jQuery in the past, and it is very easy to set up and use. Once I started working with WordPress and jQuery however, I discovered lots of fun little quirks.
First of all, it’s good to know that WordPress actually comes pre-bundled with jQuery. All you have to do is call it with a PHP command in your template’s header.php file like so (enclosed in php tags):
< ?php wp_enqueue_script('jquery'); wp_enqueue_script('jquery-core-ui'); wp_enqueue_script('jquery-tabs-ui'); wp_enqueue_script('rollover', get_bloginfo('template_directory').'/rollover.js'); wp_head(); ?>
As you can see, the last one before wp_head(); is actually a custom JavaScript file stored in the template’s directory. This is where the jQuery code for the image rollover effect is stored.
A typical jQuery script is enclosed in a function like this:
$(document).ready(function(){ jQuery script here });
Secondly, you need to enclose your jQuery code in a special block to avoid conflict with other JavaScript libraries that come with WordPress. That is done like this:
jQuery(function($) { $(document).ready(function(){ jQuery script here }); });
Following these simple steps should get your jQuery code to work within WordPress (provided your jQuery code is correct).
If anyone is interested in the code for getting image rollovers to work, please just leave a comment. I may be up for posting a tutorial for that in the future.
Tags: JavaScript, jQuery, WordPress
