How to make rollovers with jQuery

I’ve found a tutorial on Atlanta Jones. Read it, it’s worth it. Here is an example that works with the Default theme of WordPress and the Category Icons plugin with its Widget.

1. Create an empty file named rollover.js at the root of your theme folder.

2. Copy and paste this javascript code in rollover.js :

jQuery(function($) {
    $(document).ready(function(){
        // Posts
        $("#content h2>img").each(function () {
            rollsrc = $(this).attr("src");
            rollON = rollsrc.replace(/.png$/gi, "_over.png");
            $("

").attr("src", rollON);
        });

        $("#content h2>a").mouseover(function () {
            imgsrc = $(this).children("img").attr("src");
            matches = imgsrc.match(/_over/);
            if (!matches) {
                imgsrcON = imgsrc.replace(/.png$/gi, "_over.png");
                $(this).children("img").attr("src", imgsrcON);
            }
        });

        $("#content h2>a").mouseout(function () {
            $(this).children("img").attr("src", imgsrc);
        });

        // Sidebar
        $("li.cat-item>a").mouseover(function () {
            imgsrc = $(this).children("img").attr("src");
            matches = imgsrc.match(/_over/);
            if (!matches) {
                imgsrcON = imgsrc.replace(/.png$/gi, "_over.png");
                $(this).children("img").attr("src", imgsrcON);
            }
        });

        $("li.cat-item>a").mouseout(function () {
            $(this).children("img").attr("src", imgsrc);
        });
    });
});

Open the file functions.php of your theme, then copy and paste this at the beginning :

wp_enqueue_script('jquery');
wp_enqueue_script('caticons-rollover', get_bloginfo('template_directory').
                                       '/rollover.js');

and save the changes.

The script uses images that end with _over.png for the rollover images. Note that you can easily change the .png extension to .gif or .jpg in the script, if you want. If you want more details or just understand how it works, read the tutorial. Here are the images I’ve used to test it :

Moreover, it depends on the CSS structure of your index.php and sidebar.php or the widget. I think it will work for the widget as it is, but if you change the theme, you’ll probably need to change also the lines that contain ‘#content h2>a’ and ‘#content h2>img’. If this is the case, I recommend you to experiment with the help of Firebug, a VERY good plugin for Firefox that will help you to find the exact ‘CSS sequence’. Here is how I’ve done to find ‘#content h2>a’ and ‘#content h2>img’ :

1. In Firefox, activate Firebug then click on Inspect
2. Click on the category icon
3. Look at the CSS line


Click to enlarge