Friday, July 10, 2009

Cross-browser javascript to create image rollovers using predownload approach

Please visit my new Web Site

What is image rollover? Basicaly image rollover means swapping or changing images between two images when user moves the mouse cursor over the image. The most popular practice in our development life is most of the times 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 realtime aaproach for smooth image rollover with predownload technique.

<a href=""

img src="Image/Collapse.jpg" name="imgrollover" style="border:0">

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 second image start loading & after completion you will see the second image. So there is a time delay or gap for first rollover which is not accepted in commercial purpose. So we need to resolve this. My sugession in this regard is, better try to predownload(load the images into the memory cache in the page loading time) the two images first so that when user moves mouse cursor over the image at the same time the 2nd image already downloaded, thats why the user experience a smooth rollover. Look at the below complete example on how we can predownload the images to make a smooth rollover. Here when user moves the mouse over the image the 2nd rollover image will appear instantly.

<head runat="server">
<title>Image Rollover Example</title>

script type="text/javascript">
CachedImages = new Array()
CachedImages[0] = new Image()
CachedImages[0].src = "Image/Expand.jpg"
CachedImages[1] = new Image()
CachedImages[1].src = "Image/Collapse.jpg"


<form id="form1" runat="server">

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


Here look at the javascript block under head tag you will see that i use an array to predownload the images & store images into this arry when the page start loading. In the link i just refer the array contents based on mouse over & mouse out event.

Now have a look at the sample output:

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


aurimas said...


Want to say something?

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash