Home > Web Front-end > JS Tutorial > How Can I Pass Arguments to an Event Listener Function in JavaScript?

How Can I Pass Arguments to an Event Listener Function in JavaScript?

Patricia Arquette
Release: 2024-12-14 11:16:10
Original
178 people have browsed it

How Can I Pass Arguments to an Event Listener Function in JavaScript?

Passing Arguments to Event Listener Function

Consider this scenario:

var someVar = some_other_function();
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);
Copy after login

The issue here is that someVar is not accessible within the listener function of addEventListener. It's treated as a new, local variable.

Solution: Leverage Event Target's Attributes

Instead of trying to access variables from outside the listener function, retrieve the arguments directly from the event target's attributes.

For instance:

const someInput = document.querySelector('button');
someInput.addEventListener('click', myFunc, false);
someInput.myParam = 'This is my parameter';

function myFunc(evt)
{
  window.alert(evt.currentTarget.myParam);
}
Copy after login

HTML:

<button class="input">Show parameter</button>
Copy after login

This approach ensures that the necessary information is encapsulated within the event object, making it accessible when the listener function is invoked.

The above is the detailed content of How Can I Pass Arguments to an Event Listener Function in JavaScript?. 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