Home > Web Front-end > JS Tutorial > body text

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

Linda Hamilton
Release: 2024-10-25 17:50:02
Original
310 people have browsed it

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);
Copy after login

Answer:

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

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

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!