[ACCEPTED]-Why does addEventListener fire before the event if at all?-addeventlistener

Accepted answer
Score: 14

The root of your problem is here:

button.addEventListener("click", addTextNode(button.innerHTML))

You're 4 executing the function rather than passing 3 it to the event listener. Instead, pass 2 the function by reference, then get the 1 innerHTML inside the function.

function addTextNode() {
    var newtext = document.createTextNode(this.innerHTML),
        p1 = document.getElementById("p1");

    p1.appendChild(newtext);
}

var btns = document.getElementsByTagName("button");

for(i = 0; i < btns.length; i++){
    var button = btns[i]; 
    button.addEventListener("click", addTextNode);
}

http://jsfiddle.net/bn85J/

Score: 1

First, your usage of Add Event listener 15 is wrong. add event listener is expecting 14 a function reference in the second parameter 13 not a function call.

The following is a 12 function reference:

var myfunctionreference = addTextNode;

This is a function call 11 and will execute the function

var myfunctioncall = addTextNode();

In your code 10 you are actually calling the function to 9 use as the event handler instead of referencing 8 it. Here is some Reference for .addEventListener()

You should 7 be binding the event like this:

button.addEventListener("click", addTextNode);

Second, the 6 event knows the element and knows the event. Your 5 function call should be created to accept 4 the event and not an arbitrary string. Then 3 utilizing the event or "this" will 2 allow you to get your hands on the text 1 your looking for.

function addTextNode(evt) {
    var newtext = document.createTextNode(this.innerHTML),
        p1 = document.getElementById("p1");

    p1.appendChild(newtext);
}

More Related questions