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?