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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

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