+ 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
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";
};
+ 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
+ 1
That's how it would look like:
https://code.sololearn.com/W2ek8zm9sWi1/?ref=app
+ 1
You could use bind function to bind parameters with the callback.