74

In the traditional way to add event listener:

function getComboA(sel) {
    var value = sel.options[sel.selectedIndex].value;  
}

<select id="comboA" onchange="getComboA(this)">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>

But I wanted to adapt to the addEventListener way:

productLineSelect.addEventListener('change',getSelection(this),false);

function getSelection(sel){
    var value = sel.options[sel.selectedIndex].value;
    alert(value);
}

It doesn't work because I can't pass any parameter in getSelection() as the second parameter in addEventListener method? As far as I know I can only use the function name without parenthesises.

Any idea?

BTW, please look at my previous question about console.log doesn't work in Safari 6.0 Developer Inspector, I can't write any output in the console, which is frustrating.

1

4 Answers 4

147

No need to pass anything in. The function used for addEventListener will automatically have this bound to the current element. Simply use this in your function:

productLineSelect.addEventListener('change', getSelection, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

Here's the fiddle: http://jsfiddle.net/dJ4Wm/


If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:

productLineSelect.addEventListener('change', function() {
    foo('bar');
}, false);

function foo(message) {
    alert(message);
}

Here's the fiddle: http://jsfiddle.net/t4Gun/


If you want to set the value of this manually, you can use the call method to call the function:

var self = this;
productLineSelect.addEventListener('change', function() {
    getSelection.call(self);
    // This'll set the `this` value inside of `getSelection` to `self`
}, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}
4
  • 1
    great! perfect answer! Could you point out what kind of mechanism of javascript that pass a function name(I mean without parenthesises) to other function? this's really interesting to me
    – mko
    Aug 19, 2012 at 6:06
  • 3
    Invaluable answer.
    – kta
    Dec 7, 2016 at 1:42
  • 8
    In your second example, how would you later remove that event listener? The function is anonymous.
    – jkupczak
    Jun 20, 2017 at 22:47
  • I liked the idea of passing parameters to a function by wrapping it in an anonymous function in your second example, but is there any other way of doing this? Something like what the OP had posted in his question? Nov 17, 2020 at 18:31
15

In the first line of your JS code:

select.addEventListener('change', getSelection(this), false);

you're invoking getSelection by placing (this) behind the function reference. That is most likely not what you want, because you're now passing the return value of that call to addEventListener, instead of a reference to the actual function itself.


In a function invoked by addEventListener the value for this will automatically be set to the object the listener is attached to, productLineSelect in this case.

If that is what you want, you can just pass the function reference and this will in this example be select in invocations from addEventListener:

select.addEventListener('change', getSelection, false);

If that is not what you want, you'd best bind your value for this to the function you're passing to addEventListener:

var thisArg = { custom: 'object' };
select.addEventListener('change', getSelection.bind(thisArg), false);

The .bind part is also a call, but this call just returns the same function we're calling bind on, with the value for this inside that function scope fixed to thisArg, effectively overriding the dynamic nature of this-binding.


To get to your actual question: "How to pass parameters to function in addEventListener?"

You would have to use an additional function definition:

var globalVar = 'global';

productLineSelect.addEventListener('change', function(event) {
    var localVar = 'local';
    getSelection(event, this, globalVar, localVar);
}, false);

Now we pass the event object, a reference to the value of this inside the callback of addEventListener, a variable defined and initialised inside that callback, and a variable from outside the entire addEventListener call to your own getSelection function.


We also might again have an object of our choice to be this inside the outer callback:

var thisArg = { custom: 'object' };
var globalVar = 'global';

productLineSelect.addEventListener('change', function(event) {
    var localVar = 'local';
    getSelection(event, this, globalVar, localVar);
}.bind(thisArg), false);
2
  • 1
    Thank you Jeffrey Westerkamp, your answer was helpful beause of you explained it in details!
    – Yone
    Jan 24, 2018 at 7:39
  • This answer seems the best but could be improved by mentioning that creating the bound version creates a "new" function. Saving that in a variable and passing that function will also allow the use of removeEventListener. For more information see @bens aswer here: stackoverflow.com/questions/11565471/… Jun 29, 2023 at 16:26
7

When you use addEventListener, this will be bound automatically. So if you want a reference to the element on which the event handler is installed, just use this from within your function:

productLineSelect.addEventListener('change',getSelection,false);

function getSelection(){
    var value = sel.options[this.selectedIndex].value;
    alert(value);
}

If you want to pass in some other argument from the context where you call addEventListener, you can use a closure, like this:

productLineSelect.addEventListener('change', function(){ 
    // pass in `this` (the element), and someOtherVar
    getSelection(this, someOtherVar); 
},false);

function getSelection(sel, someOtherVar){
    var value = sel.options[sel.selectedIndex].value;
    alert(value);
    alert(someOtherVar);
}
0
3

If the this value you want is the just the object that you bound the event handler to, then addEventListener() already does that for you. When you do this:

productLineSelect.addEventListener('change', getSelection, false);

the getSelection function will already be called with this set to the object that the event handler was bound to. It will also be passed an argument that represents the event object which has all sorts of object information about the event.

function getSelection(event) {
    // this will be set to the object that the event handler was bound to
    // event is all the detailed information about the event
}

If the desired this value is some other value than the object you bound the event handler to, you can just do this:

var self = this;
productLineSelect.addEventListener('change',function() {
    getSelection(self)
},false);

By way of explanation:

  1. You save away the value of this into a local variable in your other event handler.
  2. You then create an anonymous function to pass addEventListener.
  3. In that anonymous function, you call your actual function and pass it the saved value of this.
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.