You can do a lot with CSS but sometimes the usage scenario just calls for the use of an image and changing the image when the user drags the mouse over the image.

I’ve been doing some refactoring on a corporate web site and their navigation menu is mandated to be image based.

You’ve probably seen code like what you see below.

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head>
   <title></title>
   <meta name="Description" content="" />
   <meta name="Keywords" content="" />  
   <script language="javascript" type="text/javascript">
       function mouseOverImage()
       {
           document.getElementById("img1").src = "push-button.jpg";
       }
     
       function mouseOutImage()
       {
           document.getElementById("img1").src = "red-button.jpg";
       }
       </script>  
   </head>
   <body>
   <img id="img1" src="red-button.jpg" alt="image rollover" 
                  onmouseover="mouseOverImage()"  
                  onmouseout="mouseOutImage()" />
   </body>
   </html>
  

It works, but it’s cumbersome and inelegant.

These days, for me, programming in JavaScript is synonymous with jQuery programming.

Here is a jQuery method that I find much more elegant.

 <html xmlns="http://www.w3.org/1999/xhtml" >
   <head>
   <title></title>
   <meta name="Description" content="" />
   <meta name="Keywords" content="" />  
   <script language="JavaScript" type="text/javascript" 
                                 src="jquery-1.4.4.min.js" />
   <script language="JavaScript" type="text/javascript">
   $(function() {
       $('img[data-hover]').hover(function() {
          $(this).attr('tmp', $(this).attr('src')).attr('src', 
                               $(this).attr('data-hover')).attr('data-hover', 
                               $(this).attr('tmp')).removeAttr('tmp');
       }).each(function() {
           $('<img />').attr('src', $(this).attr('data-hover'));
       });;
   });
   </script>
   </head>
   <body>
   <img src="red-button.jpg" data-hover="push-button.jpg" />
   </body>
   </html>
  

With the inclusion of the jQuery library and the little jQuery snippet above, any <img> tag that has a “data-hover” attribute will get the mouse-over behavior.

jQuery just ROCKS !

[ HERE is a working sample. ]