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
Patricia ArquetteOriginal
2024-12-14 11:16:10180browse

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);

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);
}

HTML:

<button class="input">Show parameter</button>

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!

Statement:
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