Question

I am trying to add an event listener to elements that have the same class by doing something like this...

// Add listener's to all elements that have a class name of "foo"
var foos = document.getElementsByClassName("foo");
for (i = 0; i < foos.length; i++) {
    var fooId = foos[i].id;
    foos[i].addEventListener('click', function(){doFoo(fooId)});
}

function doFoo(id) {
    document.getElementById("console").innerHTML += "<li>You clicked Foo " + id + "</li>";
}

The above JavaScript works other than the fact that the anonymous function argument "fooId" will always evaluate to the id of the last element of the collection - instead of the id of the item in scope of the loop.

How do I pass the id of the element id to the anonymous function parameter?

In this fiddle http://jsfiddle.net/6e4NC/ you will see that no matter which Div you click, the JavaScript will always claimed that you clicked the last Div.

Was it helpful?

Solution 2

var foos = document.getElementsByClassName("foo");
for (i = 0; i < foos.length; i++) {
   var fooId = foos[i].id;
   var f = function (fooId) {
       return function (){doFoo(fooId)};
    }(foos[i].id);
    foos[i].addEventListener('click', f);
}

Example

OTHER TIPS

function doFoo(id) {
    document.getElementById("console").innerHTML += "<li>You clicked Foo " + id + "</li>";
}

var foos = document.getElementsByClassName("foo");
for (i = 0; i < foos.length; i++) {
    foos[i].addEventListener('click', function (e) {
        doFoo(e.target.id);
    });
}

The event has the target, make use of that http://jsfiddle.net/6e4NC/3/

for (i = 0; i < foos.length; i++) {
    var fooId = foos[i].id;
    foos[i].addEventListener('click', function (e, args) {
        doFoo(e);
});

function doFoo(e) {
    var fooId = e.target.id || e.srcElement.id;
    document.getElementById("console").innerHTML += "<li>You clicked Foo " + fooId + "</li>";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top