views:

83

answers:

3

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" />
+3  A: 

You can use getAttribute in your handler, something like

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

KooiInc
it doesn't work
samuel
+1  A: 

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 ...

Jan Hančič
this worked for me:attachEvent('onclick', function() { linkClicked(link.getAttribute("command")); }, false);
samuel
A: 

I believe the a technique "javascript closure" can be used for this purpose, and it is briefly discussed here.

Salman A