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

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

DDD
Release: 2024-10-30 02:57:28
Original
763 people have browsed it

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

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

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

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!

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
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!