Image swapping using JavaScript

Image swapping


Here's the classic mouseover button effect that shows one image when it's left alone,
and another when the mouse passes over it...



<html>

<head>

</head>

<script type="text/javascript">


<!--

function PreloadImages() {

var aImages = new Array('img12.jpg','img22.jpg');

for(var i=0; i < aImages.length; i++) {

var img = new Image();

img.src = aImages[i];

}

}


//-->

</script>

<body onLoad="PreloadImages()">



<a href="index.html"

onMouseOver="document.img1.src='img12.jpg';"

onMouseOut="document.img1.src='img11.jpg';">

<img src="img11.jpg" name="img1">




<a href="javascript-examples.html"

onMouseOver="document.img2.src='img22.jpg';"

onMouseOut="document.img2.src='img21.jpg';">

<img src="img21.jpg" name="img2">



</body>

</html>

In the above JavaScript example there are two graphic buttons, one called "img11.jpg" and the other called "img21.jpg." The buttons contain onMouseOver and onMouseOut instructions that change the image objects from "img11.jpg" to "img12.jpg" and from "img21.jpg" to "img22.jpg" respectively, and back again.

The body tag has an event handler called onLoad, which calls the function PreloadImages once a page finishes loading. This function creates an array of the names of images to preload, and then creates a new Image object for each name.

This makes the browser to preload all images and store them in the cache when the page first loads, before any rollover action. It's necessary for instant image swapping

No comments: