How can I pass arguments when using event listeners? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can I pass arguments when using event listeners?

Working with a lot of elements that need to all be slightly altered in the same way can be tedious. So I tried writing a function that changes the color from red to green that in theory could work for any element. The problem is, when writing the function in the event listener it doesn’t allow me to pass an argument without prematurely executing the code. Does anyone know how I can pass an argument through an event listener? Thanks. https://code.sololearn.com/WhFY1ULjwA0s/?ref=app

4th Jan 2019, 8:14 AM
Thomas Czernek
Thomas Czernek - avatar
4 Answers
+ 2
In this case I'd use the event target. A function set as event listener will have an event object as first parameter. The event.target property allows you to access the element, that fired a certain event: elem.onload = (ev) => { ev.target.style.color = "green"; };
4th Jan 2019, 8:29 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 2
In case you want to pass some more specific arguments, you might use func.bind(null, arg_1, arg_2...). The event will be automatically added as last parameter. https://code.sololearn.com/WVw2Zi71y8S5/?ref=app
4th Jan 2019, 8:49 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 1
4th Jan 2019, 8:38 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 1
You could use bind function to bind parameters with the callback.
4th Jan 2019, 9:59 AM
Calviղ
Calviղ - avatar