How to Change an Image on a Mouse Over in HTML
Website buttons containing images that change on mouseover provide your visitors with a more dynamic experience. They also send a subtle instruction to click the button. Choose your normal-state button and the one that will display when a user rolls over the button. Use HTML and JavaScript to accomplish this useful addition to your Web page.
Instructions
-
-
1
Open a text or HTML editor and insert the following:
<SCRIPT TYPE="text/javascript">
<!--
var roArray=new Array();
function setrollover(OverImg,docImgName)
{
if (! document.images)return;
if (docImgName == null)
docImgName = document.images[document.images.length-1].name;
roArray[docImgName]=new Object;
roArray[docImgName].overImage = new Image;
roArray[docImgName].overImage.src=OverImg;
}
function rollover(docImgName)
{
if (! document.images)return;
if (! roArray[docImgName])return;
if (! roArray[docImgName].outImage)
{
roArray[docImgName].outImage = new Image;
roArray[docImgName].outImage.src = document.images[docImgName].src;
}
document.images[docImgName].src=roArray[docImgName].overImage.src;
}
function rollout(docImgName)
{
if (! document.images)return;
if (! roArray[docImgName])return;
document.images[docImgName].src=roArray[docImgName].outImage.src;
}
//-->
</SCRIPT>
-
2
Locate the area for your button and insert the following:
<A
HREF="mydoc.html"
onMouseOver = "rollover('myimage')"
onMouseOut = "rollout('myimage')"
><IMG
SRC="mainbutton.jpg"
NAME="myimage"
ALT="Home Page" BORDER=0
HEIGHT=130 WIDTH=115
></A>
<SCRIPT TYPE="text/javascript">
<!--
setrollover("overbutton.jpg", "myimage");
//-->
</SCRIPT>
Replace "mydoc.html" with your file name. Replace "mainbutton.jpg" and "overbutton.jpg" with the image names of your main and mouseover buttons respectively.
-
-
3
Save your file. Ensure the images exist in the same directory as your HTML document or at the path given in your "SRC" and "setrollover" attributes. Test by double-clicking on the file on your system.
-
1
References
- Photo Credit rodas dentadas_02 image by Pedro Nogueira from Fotolia.com