Search code examples
if-statementonmouseover

Why doesn't this Javascript succesfully change the background on the second mouseover?


The function is supposed to increment x by 1 every time it launches, thus forcing the code to choose a different option on the next launch.

function changeBackground() {
  var x = 0;
  if (x % 2 === 0) {
    document.getElementById("sample").style.backgroundColor = "purple";
  }
  else {
    document.getElementById("sample").style.backgroundColor = "white";
  }
  x++;
}
var x = document.getElementById("sample");
x.onmouseover = changeBackground;

This is just grabbing a heading and launching changeBackground every time the cursor is placed on it. The background color stays on purple.


Solution

  • because you set it to 0 every time in the beginning of the function.. you need to set the variable outside of the function

    var x = 0;
    function changeBackground() {
    if (x % 2 === 0) {
    document.getElementById("sample").style.backgroundColor = "purple";
    }
    else {
    document.getElementById("sample").style.backgroundColor = "white";
    }
    x++;
    }
    var x = document.getElementById("sample");
    x.onmouseover = changeBackground;