Search code examples
javascripthtmlonmouseover

JavaScript functions not working onmouseover


I am facing a small problem when I am trying to use functions written in JavaScript to change the styles of a <div> block, which has an id of 'div4'. I found that this code cannot work normally. The <div> was not shown when I ran these codes. Where's the problem?

function togreen() {
  document.getElementById('div4').style.width = '200px';
  document.getElementById('div4').style.height = '200px';
  document.getElementById('div4').style.backgroundColor = 'green';
}

function tored() {
  var DIV4 = document.getElementById('div4');
  DIV4.style.width = '100px';
] DIV4.style.height = '100px';
DIV4.style.backgroundColor = 'red';
}
window.onload = function() {
  var DIV = document.getElementById('div4');
  DIV.onmouseover = togreen;
  DIV.onmouseout = tored;
};
<div id="div4"></div>


Solution

  • First, there's an errant ] in the code, causing a syntax error.
    (Looks like a typo.)

    Second, the element has no initial width or height. It will not register any "mouseover" or "mouseout" events because there's nothing to hover over.

    Below, I've given it some initial size.
    I also defined DIV4 once at window.onload and reference the this from within the handlers.

    function togreen() {
      this.style.width = '200px';
      this.style.height = '200px';
      this.style.backgroundColor = 'green';
    }
    
    function tored() {
      this.style.width = '100px';
      this.style.height = '100px';
      this.style.backgroundColor = 'red';
    }
    
    window.onload = function() {
      var DIV4 = document.getElementById('div4');
      DIV4.onmouseover = togreen;
      DIV4.onmouseout = tored;
    }
    #div4 {
      width: 50px;
      height: 50px;
      background-color: lightgray;
    }
    <div id="div4"></div>