JavaScript rollover. Image swap

JavaScript rollover using image swap:

HTML code:

<a href="" onmouseover="onMouseOver()" onmouseout="onMouseOut()"><img src="out.gif" id="rollout" alt="" /></a>

JavaScript code:

	rollout=new Image();
	rollover=new Image();

	function onMouseOut(){
	function onMouseOver(){

Swap image 1 (out.gif):

Swap image 2 (over.gif):

The concept:

  1. Two images are loaded into web browser cache by a JavaScript code. One of the two preloaded images is placed in the web document by <img> HTML tag.
  2. When mouse pointer is moved over the image, the other preloaded one is displayed. When mouse pointer is moved out from the image, the initial one is displayed.

JavaScript rollover. Image swap

There were fewer practical client side options in 1990s, than today to make a web page anything beyond simple. CSS was less developed, there were non-CSS web browsers still around even in about 2000. Internet connections were too often too slow. Java and JavaScript were the main way to visual effects on a web page. Java applets being in itself a very powerful tool are more complicated to learn and implement. So JavaScript was then more than now responsible for visual effects and less for technical part - handled more by server side technologies.

But later spread of web browsers with thorough CSS support for pseudo-classes, background image positioning, custom fonts and such pushed JavaScript out of many visual effect areas. Also the Web has become more SEO aware in 2000s: this did a lot in favour of text over images and plug-ins content - that in its turn promoted the CSS case even more, taking away some of JavaScript space even more as well. As for rollovers, JavaScript ones began to be more and more often phased out in favour of CSS rollovers.

Now there are still cases when JavaScript rollovers are appropriate, but in more common situations - like rollovers used in menus - CSS ones are more suitable. So JavaScript rollovers are in a way a living past still among us. Same as centering content by table HTML tag or table borders without CSS. Oldish, but still fully functional.

For older web browsers

With some adjustments, the same code may well work in really old web browsers like Netscape 4.77, Netscape 3.04 or Opera 3.62:

1. For older Netscape and other browsers without support for id attribute: adding name attribute to the <img> tag:

<img src="out.gif" id="rollout" name="rollout" alt="" />

2. For Netscape 3.xx displaying pages from web servers not configured to send the "application/x-javascript" MIME type for .js files and other similar cases: placing JavaScript code inside HTML document only - no external JavaScript files.

Demo page ( opens in a new tab or window ) ...

Browser support
Internet Explorer 4.0+
Firefox 1.0+
Google Chrome
Opera 4.0+
Safari 3.1+
SeaMonkey 1.0+
Mozilla 0.6+
Netscape 6.01+
Firefox 1.0+
Google Chrome / Chromium
Opera 5.0+
SeaMonkey 1.0+
Mozilla 0.6+
Netscape 6.01+