I'm trying to iterate through an array of of elements and add an event listener to each one.
Populating the array:
var sliders = [].slice.call(document.getElementsByClassName("sliderControlLi"));
Iterating through the array:
sliders.forEach(function (i){
addEventListener("click", function(){
console.log("you clicked slider controler " + this.index + "!");
});
});
But with this code, whenever I click on any of the sliders I get multiple console.log printouts - once for each slider in the array.
I've looked for similar problems, but I'm still unable to solve this one.
Thanks for any help!
addEventListener? Where are you referencing the element to add the onclick?i.addEventListener(..)...sliders[i].addEventListener("click"...? If I do this, then I get an error that "sliders.addEventListener is not a function"