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?

2
  • 2
    .addEventListener("click", () => test("text i would like to pass")); Commented Oct 13, 2020 at 15:30
  • Or .addEventListener("click", test.bind(null, "text i would like to pass")) Commented Oct 13, 2020 at 15:31

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

How would you remove the eventListener in this case?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.