Home > Mobile >  How can i pass parameters to a function inside click eventlistner
How can i pass parameters to a function inside click eventlistner

Time:09-06

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.

CodePudding user response:

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>

CodePudding user response:

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));
  • Related