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.
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);
It is a default plug-in with some settings.
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