Question

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).

Was it helpful?

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.

OTHER TIPS

The reason that the handlers aren't firing when using "addEventListener" is that the string for the event name you pass using "addEventListener" must be "click", not "onclick"...

...apart from Internet Explorer where you would use "onclick", but also "attachEvent" rather than "addEventListener" as the method name for attaching event listeners to an element is different in IE! (amongst other things ;))

As to your "onclick" vs. "addEventListener"-question. With onclick, you can only assign ONE listener to a single event type, whereas by adding listeners via "addEventListener"/"attachEvent" you can have multiple callback handlers fire for a single event type, should you choose to. In your jsfiddle example it doesn't matter as there is only one handler for the event.

Additionally, "onclick" is what is known as an inline handler, depending on how you're writing your JavaScript application this could mean that you would have no access to variables part of your applications object / closures which could become an architectural problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top