Home > Article > Web Front-end > Here are some potential article titles in a question format, based on your provided content: * **Why Does My JavaScript `addEventListener` Fire on Page Load When Adding to a Dynamic Element?** * **H
JavaScript "addEventListener" Event Fires on Page Load
When attaching event listeners to elements created dynamically, it's essential to ensure that the listener is bound correctly to trigger the event at the desired time.
In the provided script, the event triggers upon page load because the event listener is added before the element is created and inserted into the DOM. To rectify this issue, the following should be considered:
The corrected script should look like this:
<code class="javascript">document.write("<div id=\"myDiv\">I am a div</div>"); el = document.getElementById("myDiv"); el.addEventListener("click", function() { alert("clicktrack"); }, false);</code>
By following these steps, the event listener will be attached to the element once it exists in the DOM, and the event will be triggered when the element is clicked.
The above is the detailed content of Here are some potential article titles in a question format, based on your provided content: * **Why Does My JavaScript `addEventListener` Fire on Page Load When Adding to a Dynamic Element?** * **H. For more information, please follow other related articles on the PHP Chinese website!