-3

I am trying to change the backgroundColor of the drumkey class when clicking on a p element. However, it is instantly applying when loading the page instead of onClick.

var keyEl = document.getElementsByClassName("drumKey");
var x = document.getElementsByTagName("p");

for (i = 0; i < x.length; i++) {
    x[i].addEventListener("click", colorChange(i));
}

function colorChange(i) {
    keyEl[i].style.backgroundColor = "red";
}
kyle
  • 691
  • 1
  • 7
  • 17
Adrian Danlos
  • 447
  • 6
  • 20

2 Answers2

3

It is because addEventListener requires a function as a second parameter and you are calling to execute a function instead of returning a function.

Remember that functions are objects in Javascript. You can just return a function like this:

var keyEl = document.getElementsByClassName("drumKey");
var x = document.getElementsByTagName("p");

for (i = 0; i < x.length; i++) {
    x[i].addEventListener("click", colorChange(i));
}

function colorChange(i) {
  return function(){
    keyEl[i].style.backgroundColor = "red";
  }    
}
<div class="drumKey">This is div 1</div>
<div class="drumKey">This is div 2</div>
<div class="drumKey">This is div 3</div>
<div class="drumKey">This is div 4</div>


<p>Click here to change the background color to red of Div 1</p>
<p>Click here to change the background color to red of Div 2</p>
<p>Click here to change the background color to red of Div 3</p>
<p>Click here to change the background color to red of Div 4</p>
Lolpez
  • 849
  • 8
  • 17
-3

so, your mistake that you call function when assign an event, but you need return it, like below

x[i].addEventListener("click", (i) => colorChange(i));
Max
  • 781
  • 7
  • 19