Home > Web Front-end > JS Tutorial > Why Does `addEventListener` Call My Function Immediately Instead of on Event Trigger?

Why Does `addEventListener` Call My Function Immediately Instead of on Event Trigger?

Linda Hamilton
Release: 2024-12-13 15:16:10
Original
584 people have browsed it

Why Does `addEventListener` Call My Function Immediately Instead of on Event Trigger?

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

We want to add a click event to the second link:

second.addEventListener('click', message_me('shazam'));
Copy after login

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:

  • Create an anonymous function: Wrap 'message_me' in an anonymous function to return a function reference:
second.addEventListener('click', function() {
    message_me('shazam');
});
Copy after login

This solution ensures that 'message_me' is called only when the second link is clicked.

  • Return a function from 'message_me': Modify 'message_me' to return a function reference:
function message_me(m_text) {
    return function() {
        alert(m_text);
    };
}

second.addEventListener('click', message_me('shazam'));
Copy after login

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!

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