monkey blot
monkey blot

Reputation: 985

function not being called, using jquery .delegate

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

Answers (4)

Starx
Starx

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

Jibi Abraham
Jibi Abraham

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

Joseph
Joseph

Reputation: 119837

it's better to do this:

$("body").delegate("div", "mouseover", function(){
   alertMe();
   //plug more code down here
});

it has advantages, mainly:

  • if you want other stuff done after the event, just add it in
  • you can call more functions in this form (rather than that single alertMe())

Upvotes: 0

tusar
tusar

Reputation: 3424

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

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

Upvotes: 1

Related Questions