"addEventListener Calls the Function Without Prompt" Explained
When attaching an event listener to an element, we want the function to execute only when the event occurs. But in some cases, it can be tricky to ensure that the function isn't called prematurely.
Consider the following HTML code:
<span>
We want to add a click event to the second link:
second.addEventListener('click', message_me('shazam'));
where 'message_me' is an external function that displays a message. Surprisingly, this code triggers the 'message_me' function immediately, even before we click the second link.
The Problem
The issue lies in the way JavaScript handles function references as the second argument of 'addEventListener'. JavaScript expects a reference to a function, but in the problematic code, the function 'message_me('shazam')' is invoked immediately, and its result is passed instead.
The Solution
There are two ways to resolve this issue:
second.addEventListener('click', function() { message_me('shazam'); });
This solution ensures that 'message_me' is called only when the second link is clicked.
function message_me(m_text) { return function() { alert(m_text); }; } second.addEventListener('click', message_me('shazam'));
In this case, 'addEventListener' receives a reference to a function that will be executed when the click event occurs.
The above is the detailed content of Why Does `addEventListener` Call My Function Immediately Instead of on Event Trigger?. For more information, please follow other related articles on the PHP Chinese website!