How to pass custom argument to event listener in JavaScript?

How can I add an event listener (addEventListener (), attachEvent ()) that also accepts a parameter?

The parameter is passed as the user attribute of the element, for example:

<img src="icon.gif" alt="Test button" command="test" />
<img src="icon2.gif" alt="Test button2" command="write" />
+3
source share
2 answers

You can use something like this:

element.addEventListener ( 'click', (function ( myParam ) {
    return function () {
        // user myParam here
    };
} ) ( yourParam ), false );

everything that you pass, since "your pairs" will be available to the event handler using the "myParam" parameter ...

+3
source

You can use getAttribute in your handler, something like

var param = this.getAttribute('command');

+3
source

Source: https://habr.com/ru/post/1725138/


All Articles