samuel
samuel

Reputation: 321

How can I pass a custom argument to an event listener in JavaScript?

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

The parameter is passed as the element's custom attribute like:

<img src="icon.gif" alt="Test button" command="test" />
<img src="icon2.gif" alt="Test button2" command="write" />

Upvotes: 3

Views: 2176

Answers (2)

Jan Hančič
Jan Hančič

Reputation: 53931

You could use something like this:

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

whatever you pass in as "yourParam" will be accessible to the event handler via the "myParam" parameter ...

Upvotes: 3

KooiInc
KooiInc

Reputation: 122906

You can use getAttribute in your handler, something like

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

Upvotes: 3

Related Questions