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?