I am learning web development and right now i'm working on vanilla javascript. I'm following a class on Udemy and everything is going well but there is a challenge where we are supposed to build a drumkit so everytime we click on a button it should trigger a function. So the solution the instructor is giving is using a for loop
var nbButtons = document.querySelectorAll(".drum").length;
for(i = 0; i<nbButtons; i++){
document.querySelectorAll(".drum")[i].addEventListener("click", handleClick);
function handleClick() {
alert("I got clicked!" + i);
}
}
So if I try to analyze the code I understand than :
We create a variable to keep track of the number of .drum elements (querySelectorAll(".drum") returns an array of all .drum elements and we get it's length. We start a loop : We start listening for clicks on the .drum element whose number is equal to i and start the function handleClick.
So I tried it and it works but I don't understand why. the loop starts when the page is loaded which means i = nbButtons very quickly (i added console.log in the loop and it does) so logically it should listen only on clicks on the last element ?
I know i'm missing something but I don't know what.
Thanks in advance