Search code examples
javascriptprototypejs

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 id="boundary1"></div>

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

firebug returns:

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


Solution

  • 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.