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
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.
1The 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"); } 2Try 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> 1