What does calling addEventLister twice do?

In your example, func will not be called twice on click, no; but keep reading for details and a “gotcha.”

From addEventListener in the spec:

If multiple identical EventListeners are registered on the same EventTarget with the same parameters the duplicate instances are discarded. They do not cause the EventListener to be called twice and since they are discarded they do not need to be removed with the removeEventListener method.

(My emphasis)

Here’s an example:

const target = document.getElementById("target");

target.addEventListener("click", foo, false);
target.addEventListener("click", foo, false);

function foo() {
    const  p = document.createElement("p");
    p.textContent = "This only appears once per click, but we registered the handler twice.";
    document.body.appendChild(p);
}
<input type="button" id="target" value="Click Me">

It’s important to note, though, that it has to be the same function, not just a function that does the same thing. That’s because it works by looking for the function on the element’s handler list, and two distinct functions — even if equivalent — aren’t the same:

const f1 = () => {};
const f2 = () => {};
console.log(f1 === f2); // false

For example, here I’m hooking up four separate functions to the element, all of which will get called:

const target = document.getElementById("target");

for (let count = 0; count < 4; ++count) {
    target.addEventListener("click", () => {
        const p = document.createElement("p");
        p.textContent = "This gets repeated.";
        document.body.appendChild(p);
    }, false);
}
<input type="button" id="target" value="Click Me">

That’s because on every loop iteration, a different function is created (even though the code is the same).

Leave a Comment