elemen.addEventListener('click',func,false);
elemen.addEventListener('click',func,false);
Will whether the func
be called twice on click on elemen
?
If yes... Is there a solution to check is the same event listener exists on elemen
?
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 sameEventTarget
with the same parameters the duplicate instances are discarded. They do not cause theEventListener
to be called twice and since they are discarded they do not need to be removed with theremoveEventListener
method.
(My emphasis)
Here's an example:
var target = document.getElementById("target");
target.addEventListener("click", foo, false);
target.addEventListener("click", foo, false);
function foo() {
var p = document.createElement("p");
p.innerHTML = "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. For example, here I'm hooking up four separate functions to the element, all of which will get called:
var target = document.getElementById("target");
var count;
for (count = 0; count < 4; ++count) {
target.addEventListener("click", function() {
var p = document.createElement("p");
p.innerHTML = "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).