Vera Perrone Vera Perrone - 5 months ago 10
Javascript Question

How can I turn this mess in a single loop?

I want to change this long piece of code in a single loop: Please help me.

itemAll[0].addEventListener('click', function () {
klik(0)
}, false);
itemAll[1].addEventListener('click', function () {
klik(1)
}, false);
itemAll[2].addEventListener('click', function () {
klik(2)
}, false);
itemAll[3].addEventListener('click', function () {
klik(3)
}, false);
itemAll[4].addEventListener('click', function () {
klik(4)
}, false);
itemAll[5].addEventListener('click', function () {
klik(5)
}, false);
itemAll[6].addEventListener('click', function () {
klik(6)
}, false);
itemAll[7].addEventListener('click', function () {
klik(7)
}, false);
itemAll[8].addEventListener('click', function () {
klik(8)
}, false);
itemAll[9].addEventListener('click', function () {
klik(9)
}, false);
itemAll[10].addEventListener('click', function () {
klik(10)
}, false);
itemAll[11].addEventListener('click', function () {
klik(11)
}, false);


I already tried this but it does not seem to work, I really dont get it why:

for (var i = 0; i < itemAll.length; i++) {
var item = itemAll[i];
item.addEventListener('click', function (item) {
klik(item);
})
}


Anyway thank you for your time, I hope someone can figure this out for me.

Answer

You can use .forEach():

itemAll.forEach(function(item, i) {
  item.addEventListener("click", klick.bind(undefined, i));
});

Better yet, you could make sure that all the elements you're working with have a common class, and then just bind a single event handler at the document level that handles clicks and checks for the target element's class. (Basically, the "event delegation" thing that jQuery allows.)

Comments