Home > Web Front-end > JS Tutorial > Why Are My Event Listeners Triggering Functions Immediately?

Why Are My Event Listeners Triggering Functions Immediately?

Mary-Kate Olsen
Release: 2024-12-22 14:19:10
Original
445 people have browsed it

Why Are My Event Listeners Triggering Functions Immediately?

Event Listeners: The Mystery of Unprompted Function Calls

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

To add click events, one might use the addEventListener method:

first.addEventListener('click', function() {
  alert('sup!');
})
Copy after login

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

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');
    }
);
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template