jQuery hoverImage plugin

At the project I’m currently reviewing they’ve used a lot of hover effects for images and links containing images. You can use CSS’s :hover for it, but that means you’ll have to add a new CSS line for each hover image and that it doesn’t work in IE6 for images. So they’ve decided to use a different approach. On all these images that needed a swap effect, they’ve added some JavaScript in the “onmouseover” and “onmouseout” and that’s something I wasn’t pleased with cause it was all cluttering the html, it asked for typo’s and they were registering handlers on the wrong events(they should have used "onmouseenter" and "onmouseleave"). And then I noticed they have jQuery registered on that same page.

Writing a plugin

I really love the cross-browser compatibility jQuery gives me out of the box and the ease of use. So it was time to write a jQuery plug-in. Let’s not bother you any longer with an introduction and show you the code for such a simple plug-in.

(function($) {
    $.fn.extend({
        hoverImage: function(options) {
            var defaults = { src: "-hover", preload: true, replaceEnd: "" };
            options = $.extend(defaults, options);

            var append = options.src.indexOf(".") == -1;

            var splitter;
            if (append) {
                splitter = options.replaceEnd + ".";
            }

            return this.each(function() {
                var obj = $(this);
                var img = obj.is("[src]") ? obj : obj.children("[src]:first").eq(0);

                if (!img.is("[src]")) {
                    return true;
                }

                var oSrc = img.attr("src");
                img.data("oSrc", oSrc);

                var hSrc = options.src;
                if (append) {
                    hSrc = oSrc.split(splitter).join(hSrc + ".");
                }
                
                img.data("hSrc", hSrc);

                if (options.preload) {
                    new Image().src = hSrc;
                }

                obj.hover(function() { img.attr("src", img.data("hSrc")); },
                          function() { img.attr("src", img.data("oSrc")); });
            });
        }
    });
})(jQuery);
 

So what does this code do?

It is a default plug-in with some settings.

  • src
    You can define a complete URL to an image to use on hover OR the string to append to the default src of the image. The default value for this is “-hover” which means that if the default src of your image is “mybutton.gif” on hover that will be replaced by “mybutton-hover.gif”.
  • preload
    Determines if you would like to preload the hover image. The default is true so your hover effect will show almost instantly.
  • replaceEnd
    This is an extra option to replace a value at the end of the default image src on hover. If your default image url is “mybutton-default.gif” and your hover image url is “mybutton-hover.gif” you need to replace “-default” at the end of the image url.

If the object on which this plug-in is called does not have a “src” attribute, it wil try to get the first child that has. The hover effect will still take place on hovering the parent, but the child its image src will be changed.

Here’s a sample of html in which the plug-in is used.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>hoverImage test page</title>
    <script src="/ClientScript/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="/ClientScript/jquery.hoverImage.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(function() {
            $(".standardImage").hoverImage({replaceEnd: "-standard"});
            $(".hoverImage").hoverImage();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <img class="standardImage" src="Imgs/button-standard.gif" />
        <img class="hoverImage" src="Imgs/button.gif" />
        <a class="hoverImage" href="#" style="display:block; width:100%;border:solid 1px black;">
            <img src="Imgs/button.gif" />
        </a>
    </div>
    </form>
</body>
</html>

Works like a charm!

Cheers and have fun!

Wesley

No Comments