I am trying to call an event handler with an argument. It works fine without an argument.
Where am I going wrong here?
var box = $("#box");
function changeColor (a) {
$(this).css("background", a);
}
box.click(changeColor("green"));
I am trying to call an event handler with an argument. It works fine without an argument.
Where am I going wrong here?
var box = $("#box");
function changeColor (a) {
$(this).css("background", a);
}
box.click(changeColor("green"));
You are calling your changeColor function instead of passing it as callback. Instead you should do :
box.click(changeColor.bind(this, "green"));
The bind method creates a new function with arguments already filled, it is almost equivalent to doing :
box.click(function () {
changeColor("green");
});
var box = $("#box");
function changeColor (a) {
$(this).css("background", a);
}
box.click(function(){
changeColor("green");
});
You are trying to assign the return value of changeColor()
to box.click()
instead of the function itself. Wrapping changeColor()
in a function as follows sets the box.click()
to the function
box.click(function(){
changeColor.call(this, "green")
});
See Fiddle