-2
function changeColor(btn){
    btn.style.backgroundColor = "red";
}
let btn1 = document.getElementById("1");
btn1.addEventListener("click",changeColor(btn1));

I know that calling a function in the "addEventListner" immediately call the function . But I do need to pass a object to my function inside "addEventListner()" because I'm planning to use only one general function to handle clicks of 10 buttons.

Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
  • No need to pass the button itself, the click event will have an `event.target` that will be the button that has been clicked. – 0stone0 Sep 05 '22 at 15:56
  • Also, avoid using `1` as an ID, that will give some troubles with selectors. – 0stone0 Sep 05 '22 at 15:56
  • A handler function gets passed an [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event) type to it. An UI event always features a [`currentTarget`](https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget) and a [`target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target) property. The OP should access the former ... `event.currentTarget.style.backgroundColor = "red";`. – Peter Seliger Sep 06 '22 at 09:30
  • Does this answer your question? [How to pass arguments to addEventListener listener function?](https://stackoverflow.com/questions/256754/how-to-pass-arguments-to-addeventlistener-listener-function) – MrUpsidown Sep 06 '22 at 09:45

2 Answers2

1

From the above comment ...

"A handler function gets passed an Event type to it. An UI event always features a currentTarget and a target property. The OP should access the former ... event.currentTarget.style.backgroundColor = "red";."

Instead of using the color changing function as callback one could implement a button specific click handler which forwards its current target to a generic function which changes the background color of any passed element reference.

function changeElementColor(elm){
  elm.style.backgroundColor = 'red';
}
function handleButtonClick(evt) {
  changeElementColor(evt.currentTarget);
}

document
  .querySelectorAll('button')
  .forEach(btnElm =>

    btnElm.addEventListener('click', handleButtonClick)
  );
<button><em>Hallo</em></button>
<button><b>World</b></button>
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
-1

You have to create an anonymous function () => changeColor(btn)

function changeColor(btn){
    btn.style.backgroundColor = "red";
}
let btn1 = document.getElementById("1");
btn1.addEventListener("click", () => changeColor(btn1));
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
Konrad
  • 21,590
  • 4
  • 28
  • 64