function initNumberElement(){
let idReference = ['zero','one','two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
let numberElementReference = [];
let temp = '0';
for (const key of idReference) {
numberElementReference.push(document.getElementById(key));
for (let i = 0; i < numberElementReference.length; i ) {
numberElementReference[i].addEventListener('click', () => {
temp = temp String(i);
changeVisualOut(temp)
})
}
}
return numberElementReference;
}
Once the elements have been retrieved from the Dom I am trying to dynamically insert an addEventListener () for each element with forEach () but every time I click on an element the event is triggered several times. Why?
Even using a for loop the dynamics remain the same
CodePudding user response:
You dont need second loop at all. In first loop you are iterating through id list and add elements into numberElementReference array. Then for all elements in numberElementReference array you are adding click handler, thats why you got multiple listeners per element (because for each item in outer loop you are registering event listeners for the whole numberElementReference array again)
You can just use one loop:
function initNumberElement() {
let idReference = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
let numberElementReference = [];
let temp = "0";
for (let i = 0; i < idReference.length; i ) {
const id = idReference[i];
const element = document.getElementById(id);
numberElementReference.push(element);
element.addEventListener("click", () => {
temp = temp String(i);
changeVisualOut(temp);
});
}
return numberElementReference;
}