Shaun Mccran

My digital playground

16
A
U
G
2011

Super small JQuery / JavaScript image mouseover script

I've been developing more and more rich content using JQuery / JavaScript and today I spent a little time researching and putting together an image mouseover script.

Sure, there are loads of them already, but I really wanted to see how compact and efficient I could get this simple bit of functionality.

Ok, so I know i'm going to be loading images based on a mouseover effect, so I don't want to leave the user with a delay when they hover over the item. So the first thing to do is create an image preloader.
view plain print about
1$.preloadImages = function()
2    {
3        for(var i = 0; i<arguments.length; i++)
4        {
5            jQuery("<img>").attr("src", arguments[i]);
6        }
7    }
8    $.preloadImages("logos/twitter_on.png", "logos/linkedin_on.png", "logos/facebook_on.png", "logos/flickr_on.png", "logos/rss_on.png");
Next we will create all our images and give them a class to use when applying our mouseover function.
view plain print about
1<img src="logos/twitter_off.png" class="rollover">
The important thing here is that the initial image state is marked with the '_off' text string. It is this part of the image source that we are going to change using JavaScript. It will basically toggle the '_off' string to an '_on' string, appearing to swap the images over.
view plain print about
1$("img.rollover").hover(
2        function()
3        {
4            this.src = this.src.replace("_off","_on");
5        },
6        function()
7        {
8            this.src = this.src.replace("_on","_off");
9        }
10    );

There is a demo of this working here: http://www.mccran.co.uk/examples/jquery-image-mouseover/, this is also the code used at the top of this page for the social media links.

Can you think of any way to make this even smaller? Or more efficient?

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Bob Clingan's Gravatar CSS3 has an opacity attribute... you might be able to use that to do the same type of thing. It would save you having to create two images.
# Posted By Bob Clingan | 17/08/2011 04:46
Shaun McCran's Gravatar Thanks Bob, I'll have a dig around and try it out. Would be interesting to see the same functionality but done through CSS3.

I've done something similar with more traditional CSS where you just move a background image around based on the class:hover styling.
# Posted By Shaun McCran | 17/08/2011 05:09
Phillip Senn's Gravatar It's nice.
# Posted By Phillip Senn | 17/08/2011 09:51
Back to top