1

I am wondering if there is a way to pass a function with parameters into an JS addEventListener?

I have tried directly binding a function with parameters to addEventListener, but the listener does not work and executes the function right away without the event being triggered.

document.getElementById("button1").addEventListener("click", test1("text I would like to pass"));

function test1(text) {
  console.log(text);
}
<button id="button1">Click Me</button>

The listener would work if the function bound does not contain any parameter:

document.getElementById("button1").addEventListener("click", test1);

function test1() {
  console.log("text I would like to pass");
}
<button id="button1">Click Me</button>

I have also tried doing the same thing using onclick but the same scenario happens. In that case, how do I bind a function with parameters to addEventListener then?

gshow8 shac
  • 391
  • 2
  • 15

1 Answers1

2

you can use () => { call your function here } or function(){ call your function here}

document.getElementById("button1")
.addEventListener("click", () => { test1("four");});

function test1(text) {
  console.log(text);
}
<button id="button1">Click Me</button>
Andam
  • 2,087
  • 1
  • 8
  • 21