Change images on mouse over with javascript. Define the images and preload them.

It can sometimes be a nice effect to change images when the mouse is moved over.

For example if you have a file archive function and have directories, then the directory images can “open” when the mouse is moved over.

Move over these images and see how the directory seem to open


Changing image...


Changing image...

This script does two nice things. First it “pre loads images”. If you don’t do this it will take a little time when the mouse is moved over an icon the first time, because the web browser needs to download the image. With pre loading we trick the browser to load the image before it is displayed.

With javascript we create new Image()-objects and assign four icons to them. Two for open/closed for the first image and two for the second. (Add more if you need more than two icons)

Then there are two functions “over” and “out” that take one parameter that tell the function what image to handle. 1 or 2 at the moment.. Those functions “simply” change the image-src into open/closed mode.

If you look at the links there are two new things. onMouseOver and onMouseOut. They are automaticly called as events when the mouse moves over or moves away from the link/image. Replace # with the file you want to be called when the link is clicked.

<script language=”JavaScript”>
<!–
// Pre load images.
if (document.images) {
img1_open           = new Image();
img1_closed         = new Image();
img2_open           = new Image();
img2_closed         = new Image();

img1_open.src      = “open1.gif”;
img1_closed.src    = “closed1.gif”;
img2_open.src      = “open2.gif”;
img2_closed.src    = “closed2.gif”;
}

function over(i)
{
if (document.images)
eval(’document.img’+i+’.src=img’+i+’_open.src’);
}

function out(k)
{
if (document.images)
eval(’document.img’+k+’.src=img’+k+’_closed.src’);
}
//–>
</script>

<a href=”#” onMouseOver=”over(1);” onMouseOut=”out(1);”>
<img name=img1 border=0 alt=”Changing image…” src=”closed1.gif”></a>

<a href=”#” onMouseOver=”over(2);” onMouseOut=”out(2);”>
<img name=img2 border=0 alt=”Changing image…” src=”closed2.gif”></a>

Similar Posts: