Image Rollovers

by Tweak on June 12, 2009
in Javascript

Ever wonder how people make those images switch over when you put your mouse over them? Like so:

Well, they probably used Javascript. This tutorial will demonstrate one of the easiest ways to accomplish the rollover effect. Near the top of your HTML code, you need to insert a preloader script that will tell the browser to download the images you wish to have appear when the mouse is hovering over them. It is usually a good idea to put this code inside the tags. The code should look like this:

<script language="Javascript">
<!--
button1up=new Image(50,50);
button1up.src="pic1up.gif";
button1down=new Image(50,50);
button1down.src="pic1down.gif";
//-->
</script>

As you can see, this code preloads the images pic1up.gif (the image at its mouseover state) and pic1down.gif (the original image). The numbers in the parentheses represent the images’ width and height (respectively) in pixels. The names you define for each state such as button1up will be called in the next step.

Farther down in your HTML code, at the location where you wish to place your rollover images, you will need to add code like the following:

<a href="somewhere.htm" onmouseover="button1.src=button1up.src" onmouseout="button1.src=button1down.src"><img name="button1" src="pic1up.gif" width=50 height=50 border=0></a>

The onmouseover attribute tells the browser to change the image named button1 to the button1up image that is defined in the preloader script as a user hovers his/her mouse over it. The onmouseout attribute tells the browser to change the image named button1 back to the button1down image that is defined in the preloader. Inside the tag, the image is named “button1.” That’s pretty much it; now your buttons will be able to roll over like the good dogs they are.

Share and Enjoy:
  • Add to favorites
  • Twitter
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Digg
  • del.icio.us
  • MySpace
  • Live
  • Yahoo! Buzz
  • PDF
  • email

Post a Comment