3

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!

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Runny Yolk
  • 1,074
  • 3
  • 23
  • 41

2 Answers2

12

You should use addEventListener() as :

target.addEventListener(type, listener[, options]);

You could also get the index from forEach :

arr.forEach(function ( element_value,element_index ){ })

Hope this helps.

var sliders = [].slice.call(document.getElementsByClassName("sliderControlLi"));

sliders.forEach(function (element, index){
  element.addEventListener("click", function(){
    console.log("you clicked slider controler " +index + "!");
  });
});
<div class="sliderControlLi">slider 1</div>
<div class="sliderControlLi">slider 2</div>
<div class="sliderControlLi">slider 3</div>
<div class="sliderControlLi">slider 4</div>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
4

You should be using

EventTarget.addEventListener(...)
^^^^^^^^^^^^

so in your case

sliders.forEach(function (elem){
    elem.addEventListener(...);
});
epascarello
  • 204,599
  • 20
  • 195
  • 236