javascript to Create Image Rollover – PreDownload Approach

What is Image Rollover? Basically image rollover means swapping or changing images between two images when user moves the mouse cursor over or out of the image. The most popular practice in our development life, most of the time our clients want to swap or change images for onmouseover(user moves mouse over the link) & onmouseout(user moves out mouse from the link) for links in the header menus or side menus. So that you can highlight a link or give an eye catching interface to your client. Here i will try to start with a simple example then i will give you a real time approach for smooth image rollover experience with “PreDownload” technique.

Cross Browser Javascript Image Rollover Code Example:

	<title> Javascript Image Rollover Example</title>

	<a href=""
	<img src="Image/Javascript_Mouse_Out.png" name="imgrollover" style="border:0"></a>

Note: I have used 2 Javascript Events – onmouseover & onmouseout

Code Explanation:
The above example is very simple & easy to implement. But the above script has one limitation. If you look at the script you will found that when the user moves the mouse over the image, only then the 2nd image starts loading. So there is a time delay or gap for first rollover which is impractical. So we need to resolve this issue. My suggestion is, better try to download first (load the images into the memory cache in the page loading time) so that after completion of the page loading, when user moves mouse cursor over the image at that time 2nd image already downloaded, that’s why the user experience a smooth rollover means the 2nd rollover image will appear instantly. Look at the below example on how we can use “PreDownload” technique to make a smooth image rollover.

Cross Browser Javascript Image Rollover Code Example (PreDownload Technique):
The Javascript code block:

<script type="text/javascript">
	CachedImages = new Array()
	CachedImages[0] = new Image()
	CachedImages[0].src = "Image/Javascript_Mouse_Over.png"
	CachedImages[1] = new Image()
	CachedImages[1].src = "Image/Javascript_Mouse_Out.png"

Using the Cached Images:

<a href=""
<img src="Image/Javascript_Mouse_Out.png" name="imgrollover" style="border:0" />

Sample Output:

Script Tested for the following Browsers:
1. Internet Explorer (IE)
2. Mozilla Firefox
4. Google Chrome

Download Code Example

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code