Home >Web Front-end >JS Tutorial >Why does my `addEventListener` trigger on page load instead of a click?

Why does my `addEventListener` trigger on page load instead of a click?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 17:50:02376browse

Why does my `addEventListener` trigger on page load instead of a click?

JavaScript "addEventListener" Event Fires on Page Load [duplicate]

Question:

Why does the following script cause the event to fire on page load instead of when the element is clicked?

document.write("<div id=\"myDiv\">I am a div</div>");
el = document.getElementById("myDiv");
el.addEventListener("click", alert("clicktrack"), false);

Answer:

The issue lies in the syntax of the event listener registration. The line:

el.addEventListener("click", alert("clicktrack"), false);

immediately executes the alert function and passes its undefined return value as the event handler. To correctly pass the alert code as a function, it should be wrapped in a function:

el.addEventListener("click", function() { alert("clicktrack"); }, false);

This way, the alert will only be called when the element is clicked, not on page load.

The above is the detailed content of Why does my `addEventListener` trigger on page load instead of a click?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn