0

I'm trying to add an event listener 'mouseover' inside a for loop using this:

<!DOCTYPE html>
<html>
<head>
    <title>BUTTONS</title>
</head>
<body>
    <button>BUTTON 1</button>
    <button>BUTTON 2</button>
<script type="text/javascript">
    var buttons = document.querySelectorAll("button");
    for(i=0;i<buttons.length;i++){
    buttons[i].addEventListener("mouseover",function(){
        this.style.backgroundColor = "gray";
    });
        }
</script>
</body>
</html>

Thankfully it worked fine. I tried experimenting the code by not using the 'this' keyword

<!DOCTYPE html>
<html>
<head>
    <title>BUTTONS</title>
</head>
<body>
    <button>BUTTON 1</button>
    <button>BUTTON 2</button>
<script type="text/javascript">
    var buttons = document.querySelectorAll("button");
    for(i=0;i<buttons.length;i++){
    buttons[i].addEventListener("mouseover",function(){
        buttons[i].style.backgroundColor = "gray";
    });
        }
</script>
</body>
</html>

because I thought inside the for-loop, everything would be translated as

buttons[0].addEventListener("mouseover",function(){
        buttons[0].style.backgroundColor = "gray";
    });

and

buttons[1].addEventListener("mouseover",function(){
        buttons[1].style.backgroundColor = "gray";
    });

which should work just fine. However, it didn't, why?

  • The scope of variable `i` is global, so at the end of the loop, the `i === buttons.length`. You can either use let or IIFE. – Ele Jun 18 '19 at 14:53

1 Answers1

1

Declare the variable in for loop with let which will create a block scope local variable. This will ensure that the i value will be rightly preserved in each iteration.

<button>BUTTON 1</button>
<button>BUTTON 2</button>
<script type="text/javascript">
  var buttons = document.querySelectorAll("button");
  for(let i=0;i<buttons.length;i++){
    buttons[i].addEventListener("mouseover",function(){
      buttons[i].style.backgroundColor = "gray";
    });
  }
</script>
Mamun
  • 66,969
  • 9
  • 47
  • 59