Problem : I would like to call a function "test " with passing parameters using the click event of the button.
using addEventListener ('click', test );
works.
using addEventListener ('click', test(parameter));
the function is activated automatically when loading and not to click on the button .
Question: how to pass parameters ?
//create 3 button (n is a counter):
var btn = document.createElement("INPUT");
btn.setAttribute("id", "demo"+n);
btn.setAttribute("type", "button");
btn.setAttribute("value", ("click"));
document.body.appendChild(btn);
call Without parameters works correcty:
function test(m) {
alert("YOU CLICKED ME!");
}
var m=0;
while(m!=3){
document.getElementById("demo"+m).addEventListener("click", test);
m=m+1;
}
`
with parameters not works (the function is activated immediately):
function test(m) {
alert("YOU CLICKED ME!"+m);
}
var m=0;
while(m!=3){
document.getElementById("demo"+m).addEventListener("click", test(m));
m=m+1;
}
Wrap your function in another function to avoid invoking it immediately
document.getElementById("demo"+m).addEventListener("click",(function(x){
return function(){
test(x);
}
})(m));
In your case addEventListener expects a function object so you can't use parenthesis in front of function as it invokes the function and passes the returning value. So you need to return the function object which invokes test function( using an anonymous function to avoid closure property of javascript functions)
EDIT: Reason for returning wrapper function of test using an anonymous function
We can't pass
function(){
test(m);
}
to addEventListener directly.
As every function object in javascript remembers the environment( in our case variable m
) outside their lexical scope . If you just create different function(like in while loop) in same environment( variable m
) then they will reference to same environment.
You have two use a function factory to avoid creating closures in loop like described above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With