How do I use onMouseOver in Javascript?

I want an image on my website to change when I hover my mouse over it. How do I do this?


I got this question from a friend who like to dabble with HTML but isn’t too much f an expert. He saw this effect on a button on a travel insurance website was trying to produce something similar. Well, you cannot implement this with plain HTML, but need to delve into Javascript and use a function called onMouseOver. This function is triggered when the mouse runs over a certain element on your page. It also has a corresponding sister function called onMouseOut which is called when you move your mouse away from the element in question. It’s important to use both functions otherwise your image won’t revert back to the original when the mouse moves away.

So, here’s the code that lets you do this:
<html>
<head>
<script type="text/javascript">
function mouseOver() {
document.b1.src ="image2.jpg";
}
function mouseOut() {
document.b1.src ="image1.jpg";
}
</script>
</head>
<body>
<a href="http://askowen.info" target="_blank" onmouseover="mouseOver()" onmouseout="mouseOut()">
<img border="0" alt="Ask Owen" src="image1.jpg" name="b1" /></a>
</body>
</html>

And here’s what it looks like:

I haven’t actually linked the image to anything, but you get the idea 😉

1 thought on “How do I use onMouseOver in Javascript?”

Leave a Reply

Your email address will not be published. Required fields are marked *