How do I create JavaScript Rollovers?
Note: JavaScript is a versatile programming language and there are many different ways to code a rollover. If you are not familiar with coding I suggest you start by copying my code and replacing the lines in red
.
In the first example we'll create an easy on/off state for a button. These 2 images will be used:
images/example1.gif
|
images/example1b.gif
|
Result
|
The code for this example has two parts. First we have some lines of code in the <head>
section of your HTML page. This code defines a variable in JavaScript, and in our case the variable is called image0. You don't need to worry about what variables are but just know that you need a different one for each rollover you want in your page. A menu with 3 buttons for example needs 3 variables.
1) Put this code in your <head> section |
<script type="text/javascript"><!--
image0 = newImage();
--></script> |
Second we have some code in the <body>
section of your HTML page. Line 1 is easy, a regular href
lets you set a destination link for your button.
2)
Put this code in your <body> section |
<a href="linktosomewhere.html"
onMouseOver="image0.src='images/example1b.gif';" onMouseOut="image0.src='images/example1a.gif';">
<img name="image0" src="images/example1a.gif">
</a>
|
Lines 2 and 3 have the code that defines what images to show when the mouse moves on and off. This is done with the onMouseOver
and onMouseOut
commands.
On line 4 we need to set the initial state of the button. This is the image shown when the page is first loaded.
Notice the many image0.src
lines, they refer to the variable we set in the <head>
code earlier.
So let's put it together in a working example:
|
<head>
<script type="text/javascript"><!--
image1 = newImage();
--></script>
</head>
<body>
<a href="linktosomewhere.html"
onMouseOver="image0.src='images/example1b.gif';" onMouseOut="image0.src='images/example1a.gif';">
<img name="image0" src="images/example1a.gif">
</a>
</body> |
In this next example we have 3 buttons. Each button has it's own set of code and --very important-- a different variable number (image1, image2, and image3
).
That's the end of the tutorial. If you are stuck, have questions or comments, take a look at the Credits/F.A.Q. for some answers and contact info.
What is it? - What do I need? - How do I do it? - Credits/F.A.Q.
Back to the Kasparius Tutorials Main Page