Here’s a followup to my first jQuery tutorial posted back in September 2007. To date, that article has been viewed 3,000 times, so I’m thrilled some people have gotten some good out of it.

Since then, I’ve honed the script even more, and wanted to share some of the improvements.

As with the first tutorial, this method makes a couple assumptions. First, it assumes your navigation buttons are within a container div identified by a unique id (ie, “nav”). It also assumes that your images follow a consistent naming scheme, such as nav_homeON.gif and nav_homeOFF.gif.

This tutorial is written as a standalone tutorial, so some code may be the same, or similar, to the original post. So here we go.

First, make sure your navigation is contained within an identifiable container:

1
2
3
4
<div id="nav">
	<a><img></a>
	<a><img></a>
</div>

Then, in your javascript, make sure your jQuery code is surrounded by the usual:

1
2
3
$(document).ready(function() {
	// jquery code goes here
});

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");

My original script then checked to see if the moused-over button was already “on”:

matches = imgsrc.match(/_over/);

This isn’t necessary with the revised method. Now all you need to check for was whether a valid image src was actually found. If so, then replace the word ‘OFF’ in the filename with ‘ON’.

1
2
3
4
5
6
7
// Fail if no image found
if (typeof(imgsrc) != 'undefined') {
	// Replace OFF with ON
	imgsrcON = imgsrc.replace('OFF', 'ON');
	// Now change the src to the 'ON' value
	$(this).children("img").attr("src", imgsrcON);
}

This method is better than the previous one as it doesn’t use regex or have to check for previously selected links. Plus, it includes better error checking to eliminate those pesky “undefined” javascript errors.

Handling the mouseout is the same as before. All you need to do is reset the image source to the value that was initially set on the mouseover, checking for the existence of a valid image src as before:

1
2
3
4
5
6
$("#nav a").mouseout(function(){
	// trap for 'undefined' errors again
	if (typeof(imgsrc) != 'undefined') {
		$(this).children("img").attr("src", imgsrc);
	}
});

I’ve also implemented a better preloading mechanism. This goes above the rollover code:

1
2
3
4
5
6
7
8
9
// Loop over each image within the navigation container
$("#nav img").each(function() {
	// Set the original src
	rollsrc = $(this).attr("src");
	// Replace OFF with ON
	rollON = rollsrc.replace('OFF', 'ON');
	newImg = new Image(); // create new image object
	$(newImg).attr("src", rollON); // set new obj's src
});

Line 2 creates a loop to run the following function for every image within the #nav div. Line 4 sets the image’s file source, and line 3 replaces ‘OFF’ with ‘ON’. Note that this version of the rollover script doesn’t care whether your buttons are gif’s or jpg’s. And the last line 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.

Thanks for checking out this tutorial. I’ve got some other things up my sleeve that I’ll be posting soon :)

Tags: ,

  • cheers! beats the way i was doing it!
  • Robert
    Do you have a version of this using a click event to activate one of images to display a thrid image. So you have an on image, off image and clicked image that stays active untl the user moves that mouse over one of the other images. I am trying to use this code for a tri state rollover.

    Thanks for providing these tutorials.
  • Yeah, it would be fairly simple. I'll work on getting something posted.
  • rgz0r
    Ah, after implementing the earlier rollover script, I came across this one. Much better & no errors!
  • Yeah, I need to do a better job of pointing people to the more recent tutorial. Glad you like it, though!
  • @OLEIRO Hmm, I'm not sure that would really work out. If I'm reading this right, the .hover event would fire on every nav item (with the .rollover class), so it would do rollovers on every single nav item on every hover. Seems like that wouldn't be the desired result.

    Also, it means that you'd have to hard-code all your image sources in the script. With my method, it doesn't matter what the images are named or how many they are, you'll never have to adjust the script to accommodate them.

    And lastly, I'm not sure why you have two nested $(document).ready() statements.
  • A short version - I used "1" and "2" instead of "on" "off":


    $(document).ready(function(){
    $(document).ready(function () {
    $(".rollover").hover(
    function(){$(this).attr("src", $(this).attr("src").replace("1.jpg","2.jpg"));},
    function(){$(this).attr("src", $(this).attr("src").replace("2.jpg","1.jpg"));}
    );
    });
    });
  • Kendra
    I viewed the "script in action" page in several browsers, but nothing happens when I roll over the images.
  • Wow, thanks for the heads up! I just upgraded to Wordpress 2.7 a couple days ago and I think that broke it. I had been including Wordpress' own jquery.js and for some reason it wasn't working in the tutorials anymore. Once I grabbed a clean jQuery 1.2.6 and put it into the tutorial folder, it started working again. That'll teach me to rely on any of WP's assets for my tutorials :) Thanks again.
  • Thanks, this works great!
  • Excellent improvements, thank you. Helped me learn a lot about JQuery in the process. JQuery seems to be the art of mastering easy techniques, it's just that there are 1 million of them. I'm down to 6 figures though :).
blog comments powered by Disqus