Rollover is an effect produced by change of an image when the user positions the mouse over it or some other event occurs. For example in addition to changing on mouseover, a different image might appear when clicked, particularly on button objects.
The simplest and shortest code for a rollover button would be
<img src="imageon.gif" onmouseover = "this.src='imageon.giff';" onmouseout ="this.src='imageon.giff';" />
JavaScript Rollover limitations and their remedies:
Though the above code will work in most modern browsers, but older ones like netscape 4 will refuse to oblige. To overcome this cross-browser problem and other problems the following remedies are generally prescribed:
Event Binding Problem: Event binding is not supported on <img> tag on older browsers, but an image can be surrounded by a link and links even in older browsers receive ‘onmouseover’ event. So the changed code would be –
<script type = "text/javascript"> <!-- function mouseon( ) { document.image1.src = "imageon.gif"; } function mouseoff( ) { document.image1.src = "imageoff.gif"; } //--> </script> ... ... <a href = "#" onmouseover = "mouseon( )" onmouseout = "mouseoff( )" > <img name="image1" id="image1" src="imageoff.gif" alt="rollover" /> </a>
Browser compatibility: Some javascript enabled but older versions of browsers does not support images[] collection. So it is better to have a check before the action:
if(document.images) { //action........ }
Image Preloading: The biggest problem is of preloading the images. If the user starts triggering rollovers when the rollover images haven’t been downloaded, a broken image will be shown. To combat this, the ‘Javascript preloading’ technique is used. Easiest way to preload an image is to create a new image object , in the <head> of the document and set the source to preload.
<!-- if(document.images) { var offimage = new Image(); offimage.src = "imageoff.gif"; var onimage = new Image(); onimage.src = "imageon.gif"; }-->
The General Practice: The general use is to make a class name indicating rollovers and having javascript to loop through the document finding these <img> tags and inferring the appropriate images to preload and then dynamically binding the event via javascript. These scripts could be written into an external .js file and cached in all pages when required.
Even after saying all these downloading extra images for rollover effects is expensive. So for using rollover effect on site navigation purpose (like menu) css: hover property is most often the right option. The following code snippet explains the idea.
a img{height: 35px; width: 70px; border-width: 0; background: top left no-repeat} a #button1 img { background-image: url(button1off.gif); } a #button1 img { background-image: url(button2off.gif); } a #button1:hover img { background-image: url(button1on.gif); } a #button2:hover img { background-image: url(button2on.gif); }