Home >Web Front-end >JS Tutorial >Why is my JavaScript `addEventListener` firing on page load instead of on click?

Why is my JavaScript `addEventListener` firing on page load instead of on click?

DDD
DDDOriginal
2024-10-30 02:57:28841browse

Why is my JavaScript `addEventListener` firing on page load instead of on click?

JavaScript "addEventListener" Event Firing on Page Load

This issue arises when the event listener is attached improperly, specifically in the provided code snippet. Here's an explanation and resolution:

In the provided code, the event listener for the "click" event is attached to the newly created div element with the id "myDiv":

<code class="javascript">el = document.getElementById("myDiv");
el.addEventListener("click", alert("clicktrack"), false);</code>

However, the issue lies within the event listener's callback function, which is an alert statement wrapped in a string:

<code class="javascript">alert("clicktrack")</code>

This code attempts to execute the alert statement immediately when the event listener is attached. Since event listeners are registered during DOM parsing and execution, the alert gets called when the page loads, not when the element is clicked.

To resolve this, the code should wrap the alert statement in an anonymous function, which can be passed to the event listener:

<code class="javascript">el.addEventListener("click", function() { alert("clicktrack"); }, false);</code>

With this modification, the alert will only be executed when the "myDiv" element receives a "click" event, as intended.

The above is the detailed content of Why is my JavaScript `addEventListener` firing on page load instead of on 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