Search code examples
javascriptdom-events

addEventListener within a loop


I don't understand why addEventListener only works outside of a loop. Using the following code, I created example in a JsFiddle (http://jsfiddle.net/E7gaZ/1/):

window.addEventListener('load', function (){
    document.getElementById('myId').addEventListener(
        'click', myHandler, false
    );
    var myClass = document.getElementsByClassName('myClass');
    for(var i=0; i<myClass.length; i++) {
        myClass[i].addEventListener("onclick", myHandler, false);
    }
});
function myHandler(ev) {
    alert(ev.target.innerHTML);
    ev.preventDefault();
}

Clicking the "myId" link while alert "myId" and prevent page reload while the other links won't call myHandler.

The following method seems to work well though (still inside the window.load event (http://jsfiddle.net/E7gaZ/2/):

document.getElementById('myId').onclick = myHandler;
var myClass = document.getElementsByClassName('myClass');
for(var i=0; i<myClass.length; i++) {
    myClass[i].onclick = myHandler;
}

Any idea why?

Edit: why would I want to use addEventListener instead of .onclick =? Because I can add multiple listeners on the same event.

Edit: thanks for the solution, guys. As a conclusion, it was working on myId because I was using the right syntax (click) and not on *myClass because the syntax was wrong (onclick).


Solution

  • I'm pretty sure this:

    myClass[i].addEventListener("onclick", myHandler, false);
    

    Needs to be:

    myClass[i].addEventListener("click", myHandler, false);
    

    To me, it doesn't make sense to attach 'onclick' as a listener.