Home >Web Front-end >JS Tutorial >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!