Reputation: 985
I want to use jquery delegate to call a function, and this works fine:
$("body").delegate("div", "mouseover", function(){
alert("it works");
});
But I also want to be able to use the same function elsewhere. So rather than writing the same function out several times, I can just declare it separately, and call it by name, right?
But written this way, I never see the alert.
function alertMe(){
alert("it works");
};
$("body").delegate("div", "mouseover", alertMe());
Upvotes: 0
Views: 251
Reputation: 78971
Creating the common event handler is easy
function alertMe(event){
//you also need to include the event object, for various actions like stopPropagation()
alert("it works");
};
$("body").delegate("div", "mouseover", alertMe);
Upvotes: 0
Reputation: 4696
jQuery .delegate
has been superseded by the .on method. I would recommend you change your code to use it.
function alertMe(){
alert("it works");
}
$("body").on("mouseover", "div", alertMe);
//$("body").delegate("div", "mouseover", alertMe) -- old method
//Note the change in postion of selector and event
Upvotes: 1
Reputation: 119837
it's better to do this:
$("body").delegate("div", "mouseover", function(){
alertMe();
//plug more code down here
});
it has advantages, mainly:
alertMe()
)Upvotes: 0
Reputation: 3424
Drop the parenthisis while defining delegate. just give the function-name
$("body").delegate("div", "mouseover", alertMe);
Upvotes: 1