Passing parameters from EventListeners.. what am I doing wrong?

Passing parameters from EventListeners.. what am I doing wrong?
0.0 0

#1

Hello!

How do I pass a parameter to a function that is triggered by an AddEventListener?

the parameter is the name of the element that was clicked… I want to do something like that but it is not working because all the functions are triggered at once, without clicking…

var a=document.getElementById(‘a’);
var b=document.getElementById(‘b’);
var c=document.getElementById(‘c’);

a.addEventListener(“click”, letter(a));
b.addEventListener(“click”, letter(b));
c.addEventListener(“click”, letter©);

function letter(simb) {
simb.innerHTML=“x”;
}

thank you very Much!


#2

The event callback parameter is not made to be used with function reference with the bracket. In your case all three was fired because the callback method is being invoked.

You’ll have to remove the brackets for it to work. As to what you want to do with the event listener, you’ll have to give us more details.


#3

Thank you, yes I have been using it without brackets usually and it works fine.

the code I wrote is pretty much what I’m trying to achieve: in that case, I want to write “X” in the element that has been clicked (without having to write a specific function for any element…)

thanks


#4

I have been working on something similar for my TicTacToe project just recently.
Basically, I wanted to add event listeners on a bunch of (9 in total) divs and then have a function that handle what happens based on which div you click. I believe this is exactly what you are doing?

So in html under each div I have the same "key" class:
<div data-position="0" class="key"></div> <div data-position="1" class="key"></div> <div data-position="2" class="key"></div> etc....

Then I use one of those new arrow functions to slap event listeners on all the divs that have this specific class:
const keys = Array.from(document.querySelectorAll('.key')); keys.forEach(key => key.addEventListener('click', action));

And lastly, for the action click handling function I pass the click handle object (not sure if it is an object?) and target the div with e.target.innerHTML = "X", like so:
function action (e) { e.target.innerHTML = "X" }

I am unsure if this method is better, but I just wanted to share my solution and what worked for me as an alternative to think about :slight_smile:


#5

You can use “this” for eventListeners. The element being clicked is “this”.
So you should change your code to something like this

var a=document.getElementById(‘a’);
var b=document.getElementById(‘b’);
var c=document.getElementById(‘c’);

a.addEventListener(“click”, letter);
b.addEventListener(“click”, letter);
c.addEventListener(“click”, letter);

function letter() {
this.innerHTML=“x”;
}


#6

An alternative is put the event on the element tag itself. For instance:

Input type=‘button’ onclick=“hello(40)”

Then in your function, it will print out 40.