Image Rollovers

Contact Us or call 1-877-932-8228
Image Rollovers

Image Rollovers

Image rollovers are commonly used to create a more interesting user experience and to help highlight navigation points. When the user hovers the mouse over an image, the source of the image is modified, so that a different image appears. When the user hovers the mouse back off the image, the original source is restored. The code below shows how to create a simple rollover.

Code Sample:

ImagesWindowsTimers/Demos/SimpleRollover.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Simple Image Rollover</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div style="text-align:center;">
<h1>Simple Image Rollover</h1>
<img name="MyImage" src="Images/Banner.jpg"
	onmouseover="this.src = 'Images/Hulk.jpg';"
	onmouseout="this.src = 'Images/Banner.jpg';">
<p>Who are you calling simple?</p>
</div>
</body>
</html>

The mouse-over event is captured with the img tag's onmouseover event handler. When this happens, the following JavaScript code is called:

this.src = 'Images/Hulk.jpg';

The this object refers to the current object - whatever object (or element) the this keyword appears in. In the case above, the this object refers to the img object, which has a property called src that holds the path to the image. The code above sets the src to "Images/Hulk.jpg".

Likewise, the mouse-out event is captured with the img tag's onmouseout event handler. When this happens, the following JavaScript code is called:

this.src = 'Images/Banner.jpg';

This code sets the src to "Images/Banner.jpg," which is what it originally was.

An Image Rollover Function

Image rollovers can be handled by a function as well:

Code Sample:

ImagesWindowsTimers/Demos/SimpleRolloverFunction.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Simple Image Rollover Function</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
function imageRollover(img, imgSrc){
	img.src = imgSrc;
}
</script>
</head>
<body>
<div style="text-align:center;">
<h1>Simple Image Rollover Function</h1>
<img name="Banner" src="Images/Banner.jpg"
	onmouseover="imageRollover(this, 'Images/Hulk.jpg');"
	onmouseout="imageRollover(this, 'Images/Banner.jpg');">
<img name="Bruce" src="Images/Bruce.jpg"
	onmouseover="imageRollover(this, 'Images/Batman.jpg');"
	onmouseout="imageRollover(this, 'Images/Bruce.jpg');">
<p>Who are you calling simple?</p>
</div>
</body>
</html>
Next