When working with event listeners, one may encounter a puzzling behavior: adding an event listener with an external function reference seems to invoke the function immediately, even without clicking on the element. This can be frustrating and lead to unexpected behavior.
Consider the following HTML snippet:
<span>
To add click events, one might use the addEventListener method:
first.addEventListener('click', function() { alert('sup!'); })
This code works as expected, triggering an alert when the "First Link" is clicked. However, when using an external function as the second argument:
function message_me(m_text) { alert(m_text) } second.addEventListener('click', message_me('shazam'))
The message_me function is invoked immediately, resulting in an alert message even before the "Second Link" is clicked.
To resolve this issue, one needs to understand that the second parameter of addEventListener expects a function reference. In the problematic code, the function is being invoked directly and its result is passed to addEventListener. Instead, either an anonymous function should be used as the second argument or the external function should be modified to return a function.
For example, we can use an anonymous function within addEventListener:
function message_me(m_text) { alert(m_text) } second.addEventListener('click', function() { message_me('shazam'); } );
By providing a function reference within the anonymous function, we ensure that the message_me function is only invoked when the "Second Link" is clicked.
The above is the detailed content of Why Are My Event Listeners Triggering Functions Immediately?. For more information, please follow other related articles on the PHP Chinese website!