Use jQuery to create an image rollover effect and preload all images.

It’s been a busy couple weeks. I’ve been moving all my sites to a new server and performing upgrades. I finally have everything up and running again and thought I would share a snippet of code. A client was using some really old javascript and I’ve been upgrading their site, and cleaning up their code. I strongly believe in writing solid, re-usable code snippets and always think about how I can write a piece of code so that I don’t have to re-write that same code again for the next project. Whenever I develop software, I’m constantly pulling code snippets from my code library and integrating them into the new project. The less work I have to do to add functionality the better.

Here’s a simple jQuery style image rollover effect with preloading of all images that I created for a recent client. You’ll notice this code can simply be plugged into any site and will function appropriately with minimal fuss.


Example

Mouseover the image below to see it in action.


The Code

Add the following to your header, or javascript include file.

var swec_image_hover = {
    /*
        <img class="image_hover" src="/images/image1.gif" 
             hover="/images/image2.gif" alt="Image Hover Example" >
    */
    init : function() {
        var preImages = new Array();
        $(".image_hover").each(function(i){
            var img = new Image();
            img.src = $(this).attr("hover");
            preImages.push(img);
        });

        $(".image_hover").hover(function(){
            var src = $(this).attr("hover");
            $(this).attr("hover", $(this).attr("src"));
            this.src = src;
            $(this).css("cursor", "pointer");
        },
        function(){
            var src = $(this).attr("hover");
            $(this).attr("hover", $(this).attr("src"));
            this.src = src;
            $(this).css("cursor", "normal");
        });
    }
}


$(document).ready(function(){
    swec_image_hover.init();
});

Then to add hover functionality to any image, you can add

class='image_hover'

and

hover='/images/image2.gif'class='image_hover'

to your image tag. The full tag looks like this

<img class='image_hover' src='/images/image1.gif' hover='/images/image2.gif'>

With the addition of the image_hover class, and the included javascript, all hover images are preloaded, and any mouseover event causes the image rollover effect. Simple. Clean. Re-usable.

Leave a Reply

Your email address will not be published.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*