Simple image roll-over effect with jQuery

Here is a simple jQuery method to enable image roll-over effects (hover). This method is suitable for content editors who can add images only through TinyMCE or normal upload –  naming image files specially is the only requirement. No CSS, Javascript or other knowledge needed by the person who needs to add the images with roll-overs.

Just include this script on your HTML page and it will automatically scan image filenames, detects image filenames with special roll-over marker strings and then applies the roll-over effect on them. Roll-over images are preloaded to avoid image blinking on slow connections.

The script:

 * Automatic image hover placement with jQuery
 * If image has -normal tag in it's filename assume there exist corresponding
 * file with -hover in its name.
 * E.g. ->
 * This image is preloaded and shown when mouse is placed on the image.
 * Copyright Mikko Ohtamaa 2011

(function (jQuery) {
        var $ = jQuery;

        // Look for available images which have hover option
        function scanImages() {
                $("img").each(function() {

                        $this = $(this);

                        var src = $this.attr("src");

                        // Images might not have src attribute, if they
                        if(src) {

                                // Detect if this image filename has hover marker bit
                                if(src.indexOf("-normal") >= 0) {

                                        console.log("Found rollover:" + src);

                                        // Mangle new URL for over image based on orignal
                                        var hoverSrc = src.replace("-normal", "-hover");

                                        // Preload hover image
                                        var preload = new Image(hoverSrc);

                                        // Set event handlers

                                        $this.mouseover(function() {
                                                this.src = hoverSrc;

                                        $this.mouseout(function() {
                                                this.src = src;




\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

3 thoughts on “Simple image roll-over effect with jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *