Change Image onMouseOver Using JavaScript
Changing the appearance of an image when the user scrolls over it with the mouse pointer is a good way to indicate clickable links or other useful functionality on your website (or simply to flex your graphical muscle). I've seen numerous examples of how to do this, but many of them involve long JavaScript functions to do it, which can be hard to maintain. I've developed something much simpler...
Rather than defining image names, ID's, and writing an elaborate functions to modify images, we're just going to add onMouseOver and onMouseOut events to each image. Simple as pie.
In the below example, I have a link with the image that will change inside. Initially the image displays the "off" version then uses onMouseOver and onMouseOut to set the appropriate "on" and "off" images should the mouse pass over them.
<a href="default.aspx">
<img src="layout/home_off.gif" alt="Home" border="0"
onmouseover="this.src='layout/home_on.gif';"
onmouseout="this.src='layout/home_off.gif';" />
</a>
<a href="archive.aspx">
<img src="layout/archive_off.gif" alt="Archive" border="0"
onmouseover="this.src='layout/archive_on.gif';"
onmouseout="this.src='layout/archive_off.gif';" />
</a>
<a href="search.aspx">
<img src="layout/search_off.gif" alt="Search" border="0"
onmouseover="this.src='layout/search_on.gif';"
onmouseout="this.src='layout/search_off.gif';" />
</a>
This gets you 90% of the way. You'll probably notice a lag the first time you scroll over you images. This is because it must load the image from the web server to your local computer so that it can be displayed. In order to get around this, we need to preload the images. A really simple way to do this is by tucking all the images you need to preload in a hidden div. This way, they're ready right away when you need them but they're not displayed on the screen.
<div class="hiddenDiv">
<
This article has been view 46922 times.
|