Subscribe to my RSS feed RSS
July 28, 2008

How do I use onMouseOver in Javascript?

  • Written by Owen under web development |
  • No comments yet |

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 ;)

Feed for this Entry | Trackback Address

No comments yet

There are no comments yet, be the first!

Leave a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>