Rollover effect with JavaScript
One of the things that makes JavaScript so useful is that it is an object oriented scripting lanugage. This is very useful because it allows you to control sections of web pages at certain times, and you do not have to reload the entire page to do so. One of the things you can do with this type of structure is a simple rollover, like the one below.
<table> <tr> <td><a href="#" onmouseover="document.arrow1.src='images/arrow.jpg'" onmouseout="document.arrow1.src='images/blank.jpg'">LINK1</a></td> <td><a href="#" onmouseover="document.arrow2.src='images/arrow.jpg'" onmouseout="document.arrow2.src='images/blank.jpg'">LINK2</a></td> <td><a href="#" onmouseover="document.arrow3.src='images/arrow.jpg'" onmouseout="document.arrow3.src='images/blank.jpg'">LINK3</a></td> </tr> <tr> <td align="center"><img src="images/blank.jpg" name="arrow1" align="center"></td> <td align="center"><img src="images/blank.jpg" name="arrow2" align="center"></td> <td align="center"><img src="images/blank.jpg" name="arrow3" align="center"></td> </tr> </table>
Lets look at what we know is happening in the script. As you can tell, we have a simple HTML table that is three by two. The first row has three links in it, where as the second row has three image tags. We also notice that the name of the image tags are arrow1, arrow2, and arrow3 in that order from left to right. Looking more in depth, you may have seen the JavaScript event handlers, the onmouseover and onmouseout. By using these two JavaScript event handlers we create the effect that we want. The event handler onmouseover, tells JavaScript to do something when the mouse comes in contact with that part of the page, in this case the hyperlink. The second event handler, just says when the mouse moves off, or in not in contact with the link, then preform another action. Without the onmouseout part of the code, the image will stay the same after the mouse moves off the link, and does not give us the complete rollover effect. This is were the object oriented part of JavaScript comes into play. Since we named each of our image tags, and we want the source for those to change, we tell the browser to do that with the document.arrow1.src. The document, is our current window in the browser, and the arrow1, is the image tag named arrow1, and the src is telling JavaScript to use the source provided. Here is what that code looks like in action.
| LINK1 | LINK2 | LINK3 |
![]() |
![]() |
![]() |
Using different images, you could create a more detailed rollover that would invert the colors on image when it is rolled over, of have a lightbulb that turns on and off. The great thing about a simple rollover is that it can be done in one line of code, like the one below.
Code:
<img src="images/lightbulb_off.jpg" onmouseover="this.src='images/lightbulb_off.jpg'" onmouseout="this.src='images/lightbulb_off.jpg'">
iEntry 10th Anniversary
CSS Snippets
JavaScript Snippets