Easy, Reusable Image Rollovers with jQuery

It also assumes your navigation is structured thusly:

<div><a><img></a><a><img></a></div>

First, make sure your jQuery code is surrounded by the usual:

1
2
$(document).ready(function() {
});

Now set up the mouseover event:

1
2
$("#nav a").mouseover(function(){
});

Next, set the source (src) of the image file. This is done by finding the child of the link that was moused over, in this case, an image.

imgsrc = $(this).children("img").attr("src");

We’ll only perform the rollover if the image state is not already “ON”.

matches = imgsrc.match(/_over/);

If it’s not, add the ‘_over’ bit to the filename and change the image source with attr(“src”):

1
2
3
4
if (!matches) {
	imgsrcON = imgsrc.replace(/.gif$/ig,"_over.gif");
	$(this).children("img").attr("src", imgsrcON);
}

And that’s it! Handling the mouseout is pretty simple. All you need to do is reset the image source to the value that was initially set on the mouseover:

1
2
3
$("#nav a").mouseout(function(){
	$(this).children("img").attr("src", imgsrc);
});

One more thing. If you have a lot of nav images, or they are not tiny files, you might want to preload them. Here is a function that will automatically preload all the images within the #nav div:

1
2
3
4
5
$("#nav img").each(function() {
	rollsrc = $(this).attr("src");
	rollON = rollsrc.replace(/.gif$/ig,"_over.gif");
	$("<img>").attr("src", rollON);
});

Line 1 creates a loop to run the following function for every image within the #nav div. Line 2 sets the image’s filename, and line 3 replaces ‘.gif’ with ‘_over.gif’. You can replace .gif with .jpg or whatever. And line 4 creates a new image element with the ON state of the image.

You can see the script in action here.
Download the .js file here.

http://atlantajones.com/web-dev/easy-reusable-image-rollovers-with-jquery/

One thought to “Easy, Reusable Image Rollovers with jQuery”

  1. script language=”JavaScript” type=”text/javascript”
    $(document).ready(function() {
    var defaultimage = $(“#imageChanger”).attr(“src”);
    $(“#nav a”).mouseover(function(){
    var imgsrc=$(this).attr(“rel”);
    $(“#imageChanger”).attr(“src”, imgsrc);
    });//end mouse over

    $(“#nav a”).mouseout(function(){
    $(“#imageChanger”).attr(“src”, defaultimage);
    });//end mouse over

    });//end function
    /script

Leave a Reply