Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventHandler to every element in a class

Tags:

javascript

I'm trying to add an event listener to all elements with a class of section, however it only applies it to the last object in the node list.

var section = document.querySelectorAll('.section');
for(var i=0;i<section.length;i++){
var elem = section[i];
elem.addEventListener('click', function () {move (elem)}, false); 
}

Is there a way I can add the event listener for each one?

like image 524
user1886695 Avatar asked Dec 07 '12 21:12

user1886695


People also ask

Can I add event listener to multiple elements?

In JavaScript, event listeners have to be attached to individual elements. You can't attach them to an array or node list of matching elements like you might in jQuery.

Can we use addEventListener to bind multiple listeners to a node in Dom?

The addEventListener() methodYou can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.

How do I add an event listener to Li?

appendChild(newListItem); // add created "li" element to "ul" newListItem. className = "item"; // add class to new "li" element newListItem. appendChild(x); // add a "span" to new "li" element var itemText = document. getElementById("newInput"); // read current input value itemText.


2 Answers

The issue is that there's no block scope in JavaScript. So elem is overwritten each iteration, instead of being declared as a new variable each time. The only way to declare new variables in each iteration is through a function:

for(var i = 0; i < section.length; i++){
  (function(elem) {
    elem.addEventListener('click', function() { move(elem); }, false);
  })(elem);
}

But addEventListener sets this to the element, so in your case you can neatly do:

for(var i = 0; i < section.length; i++){
  elem.addEventListener('click', function () { move(this); }, false);
}
like image 72
pimvdb Avatar answered Sep 23 '22 01:09

pimvdb


that's because you are referencing elem and i inside function. I can suggest trying

var section = document.querySelectorAll('.section');
for(var i=0;i<section.length;i++){
    var handler = (function(ind){ 
        return function () {
             move (section[ind]);
        }
    })(i) 

    elem.addEventListener('click', handler, false); 
}
like image 22
Eugeny89 Avatar answered Sep 26 '22 01:09

Eugeny89