March 24, 2012

function not being called, using jquery .delegate

Question by monkey blot

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());

Answer by tusar

Drop the parenthisis while defining delegate. just give the function-name

$("body").delegate("div", "mouseover", alertMe);

Answer by Starx

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);

Please fill the form - I will response as fast as I can!