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.