Categories:
Partners

Creating an image rollover effect

<html>
<head>
<script type="text/javascript">
<!--
image01= new Image()
image01.src="1.gif"
image02= new Image()
image02.src="3.gif"
//-->
</script>
</head>

<body>
<a href="whatever.htm" onmouseover=
"document.images['example'].src=image02.src" onmouseout=
"document.images['example'].src=image01.src">
<img src="1.gif" name="example"></a>
</body>

</html>

Example:

See how easy that was? By assigning a new image to the src property of the image each time the onMouseover event handler is fired inside an image link, we change the image onMouseover.

The above will work and produce the effect. However, if you're looking to add the effect to multiple images on your page, creating a rollover function is recommended. Lets rewrite the above code to do just that:

<html>
<head>
<script type="text/javascript">
<!--
image01= new Image()
image01.src="test.gif"
image02= new Image()
image02.src="test3.gif"

function rollover(imagename, newsrc){
document.images[imagename].src=newsrc.src
}
//-->
</script>
</head>

<body>
<a href="#" onmouseover="rollover('example', image02)"
onmouseout="rollover('example', image01)">
<img src="test.gif" name="example">
</a>
</body>

</html>

Now the same function can be used easily on multiple images on your page to apply a rollover effect to them!