Link and Image Rollovers

 

Introduction.  We just did some work with onClick events on links to develop some background on how JavaScript can be implemented within HTML link tags.  Now we want to develop some code based on onMouseOver and onMouseOut events to replicate the sorts of rollovers that are so associated with JavaScript.  This is not very different from what we have done, but due to the types of the events we will be using the changes in the page will be more of a surprise.

You'll make use of the Circle.gif and Square.gif as the basis of our rollovers.  Another very important issue has to do with the capability of using our link events with images.  It is not possible to put JavaScript event code within image tags.  We need to use the onClick, onMouseOver and onMouseOut events with link tags.  This is not any real problem because it is possible to use images as links.

The following code should be placed in a file called RolloverSquaredCircle.html.

 

<html>
<head>
<title>Rollover for Squaring the Circle</title>
</head>

<body>
<P><center>

<a href="#"

onMouseOver="window.document.MyImage.src='images/Square.gif';"
onMouseOut="window.document.MyImage.src='images/Circle.gif';"
onClick="return false;">
<img src="images/Circle.gif" name="MyImage" border="0"></a>

</center>
</P>
</body>
</html>

 

This relatively simple piece of code changes which image is used for the link as the user moves over it and off of it.  The initial link is the Circle.gif. 

The last thing to notice is that we have made sure there is no border around the image as it appears for the link.  This makes the appearance a little better so that certain edges of the gif files don't show.

After uploading this file and accessing it you should see the following two images as you rollover and roll off the image.

 

 

Now when you move your pointer over the image it automatically changes to the following.

 

 

Then it changes back as you roll off.

Rollovers That Link.  One last modification is to have the onClick event also work.  This requires making use of the window.location that we have used once previously.  You should call the following code RolloverSquaredCircleClick.html.

 

<html>
<head>
<title>Rollover for Squaring the Circle</title>
</head>

<body>
<P><center>

<a href="#"

onMouseOver="window.document.MyImage.src='images/Square.gif';"
onMouseOut="window.document.MyImage.src='images/Circle.gif';"
onClick="window.location='http://birdstone.org';">
<img src="images/Circle.gif" name="MyImage" border="0"></a>

</center>
</P>
</body>
</html>

 

So now if you click on this image it will take you to a friend's webpage.