Javascript: OnMouseOver – OnMouseOut

This tech recipe describes a simple image link which changes upon placing the mouse over the image.


OnMouseOver is a reasonable universal after IE4. I even believe it should work in the new Netscape engine.

What You Will Need:
1) Two images, preferably the same size (for aesthetic purposes)
2) Basic text editor (Notepad or an equivalent)

-The displaying will not allow all the tags, so replace * by < and $ by >.

The Code:

*html$
*head$
*title$onMouseOver JavaScript*/title$
*script language="Javascript"$
*!--
if (document.images)
{
preimage = new Image
afterimage = new Image
preimage.src = "image1.gif"
afterimage.src = "image2.gif"
}
--$
*/script$
*/head$
*body$
*a href="http://www.tech-recipes.com"
onMouseOver="document.roll.src=afterimage.src"
onMouseOut="document.roll.src=preimage.src"$

*img src="image1.gif" border=0 name="roll"$*/a$
*/body$
*/html$

-The Javascript part of this code needs to be placed between the head /head tags.
-The spacing of the Javascript code is important. It must be oriented as above, or very similarly, for the code to be understood properly.

*NOTE that the code is placed inside of !– — tags. The < > is in case the browser does not support Javascript. Then the code inside the tags can be ignored and the page will be displayed omitting the single operation.

-Preimage is the image to be displayed first. The location in this source should match the image to be displayed inside the body of your html file.
-Afterimage is, of course, the image to be displayed while the mouse is placed over the image.

-Document points to the current html page. It is similar to this in java.

-The image is named roll so that the images associated with the rollover effect can be preloaded in the head to associate to this name.

*Most names can be changed, just be sure to change all occurances of the same name!!

Questions/Comments: [email protected]
-William. ยง (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.