This article is an expansion upon my last article which discusses how to set up jQuery in WordPress. In this article, you will learn how to create a simple rollover image using jQuery.
First of all, you need to have your images created of course. For the sake of this article, the images should be named imagename.png, and imagename-hover.png (or any other picture file extension).
As you learned in the previous article, you need to enclose your jQuery function in a special function of its own.
This is called from an external .js file, and will work for any images inside of a div called #quote (or whatever fits your website).
jQuery(function($) { < --This is the enclosing function $(document).ready(function(){ <--This is the overall jQuery function $("#content #quote img").each(function () { <--This function determines img src rollsrc = $(this).attr("src"); rollON = rollsrc.replace(/.png$/gi, "-hover.png"); $("<img>").attr("src", rollON); }); $("#content #quote a").mouseover(function () { < --This displays the -hover image imgsrc = $(this).children("img").attr("src"); matches = imgsrc.match(/-hover/); if (!matches) { imgsrcON = imgsrc.replace(/.png$/gi, "-hover.png"); $(this).children("img").attr("src", imgsrcON); } }); $("#content #quote a").mouseout(function () { <--This returns the image to normal $(this).children("img").attr("src", imgsrc); }); }); });
The first part of each of the 3 functions that actually change the image contain a css path to the hyperlink (‘a’ tag). This will vary depending on the structure of your website. A good way to find the css path is to use the Firefox plugin called FireBug.
I hope this helps other developers in their WordPress and jQuery endeavors!
Tags: JavaScript, jQuery, WordPress
