You have probably seen plenty of pages that do a mouse rollover effect. How do you do this with javascript? Read below to find out!
<img src="someimage.jpg" />
Here you have an image. You want that image to change to something else when your mouse is over it.
To make an image change when you mouse over it, you need to add an onmouseover property to your img tag. The onmouseover is where you call a function that will change the image. Give your image an id. This will make it easier to change to a different image when you mouse over it. In the function call, you should pass the argument this.id, so the function will know which image you moused over.
<img src="someimage.jpg" onmouseover="rollover(this.id)" id="someimage" />
Next, create a Javascript function that corresponds with the one in onmouseover. You can test the function below to make sure that it works. Roll over the image in the grey box, and it should pop up an alert window with the image id in it.
<script type="text/javascript">
function rollover(my_id) {
alert(my_id);
}
</script>
<img src="someimage.jpg" onmouseover="rollover(this.id)" id="someimage" />
This works so far, but let's change the function to update the image when you mouse over it, instead of popping up an alert window.
<script type="text/javascript">
function rollover(my_id) {
document.getElementById(my_id).src = "someimage2.jpg";
}
</script>
<img src="someimage.jpg" onmouseover="rollover(this.id)" id="someimage" />
So far so good, but now we need to change it so it will make the image go back to the way it was when you move the mouse away from it.
You need to add an onmouseout property to the function to handle when the the mouse moves away from the image. You need to put a javascript function name in that property, and the function needs to put the image back the way it was.
<script type="text/javascript">
function rollover(my_id) {
document.getElementById(my_id).src = "someimage2.jpg";
}
function mouseaway(my_id) {
document.getElementById(my_id).src = "someimage.jpg";
}
</script>
<img src="someimage.jpg" onmouseover="rollover(this.id)" onmouseout="mouseaway(this.id)" id="someimage" />
There you have it! It works as expected. Now you know how to do a rollover script.
If you liked this page, please check out the JavaScript Guide for more tips, and visit Thonky.com to find more fun and helpful stuff that I have made.