Change color of element onMouseOver using javascript

I'm writing javascript which will change the color of an element when the mouse hovers over it. I know perfectly how to do this using jQuery, but this time around I have to do it using either pure JS or Prototype.

Why doesn't this work:

<div></div>

document.getElementById("boundary1").onmouseover(function() { alert("test"); }) 

firebug returns:

TypeError: document.getElementById(...).onmouseover is not a function

0

5 Answers

Your syntax is wrong, you may be thinking a little too 'jQuery', try this:

var boundary = document.getElementById('boundary'); var mouseOverFunction = function () { // this.style.color = '#000'; // your colour change }; boundary.onmouseover = mouseOverFunction; 

I've separated the logic to make the development and logic clearer, it makes your functions reusable too.

1

The Prototype way to do this would be this:

$('elementId').observe('mouseenter', function(evt){ this.setStyle('background-color: yellow'); }).observe('mouseleave', function(evt){ this.setStyle('background-color: inherit'); }); 

But as others have already pointed out, the real way to do this is with CSS. The only reason I could imagine needing to do it in JS is if you have to support IE <= 8, which doesn't like to do the :hover pseudo-class on anything except the A tag.

Try:

document.getElementById("boundary1").onmouseover = function() { alert("test"); } 

More Info.

2

Try this code

<td onMouseOver="this.bgColor='#00CC00'" onMouseOut="this.bgColor='#009900'" bgColor=#009900> <A HREF="#">Click Here</A></TD> 

You can do it using CSS

<style> .changecolour:hover { background-color:yellow; } </style> 

Now for the text you want to change color

<span class ="changecolour">Color changes when mouse comes here.</span> 

Reference :

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like