How to pass Event as a parameter in JQuery function
There are two mistakes in your solution you will have to change
var
is only used to define a variable not a parameter of a function
function buttonClick(event)
{
$("#displayArea").text(event.data.key1);
}
The other thing is the way you are assigning the event handler.
You're assigning the return value of buttonClick(event)
which will be undefined
. Just pass it the function itself. The event
object will be passed automatically by jQuery
$("#Button1").bind("click",
{ key1: "value1", key2: "value2" },
buttonClick);
You need to pass a function reference
as the click handler, but what you are doing here
$("#Button1").bind("click",
{ key1: "value1", key2: "value2" },
buttonClick(event));
is calling buttonClick(event)
immediately and which return undefined
and sets that as the click handler
. You have to pass a function reference like buttonClick
and you will get event param automatically (jQuery will send that when calling the handler).
Full Code:
$(function(){
$("#Button1").bind("click",
{ key1: "value1", key2: "value2" },
buttonClick);
function buttonClick(event)
{
$("#displayArea").text(event.data.key1);
}
});
Demo: http://jsfiddle.net/joycse06/cjc9r/
Update (Based On @Tadeck's comment):
Your code will work fine if you use function expression
like this
var buttonClick = function(event){
$("#displayArea").text(event.data.key1);
};
And you have to place this above its first use
. In this case before
$("#Button1").bind("click", ...
Because function expressions
are not hoisted
at the top of current scope like function declaration
. So you can use them only after
the expression
has been interpreted
by JS interpreter
.