Michel
Michel

Reputation: 23615

Jquery: add existing function to an Jquery event

in all jquery examples i see this kind of code:

$('.menu a').each(function(){
 $(this).animate({paddingLeft: $(this).width()}, 200);
 });

What they do here is create a function 'on the fly' (is that called an anonymous delegate?)

but what if i have an existing function, which wants to have access to the $(this) also?

let's say i have this function:

function doAnimate(ctl){
  //do something here
{

How can i use that function in the jquery statement?

Reason i ask is that i want to use this function in more jquery statements, and i don't want to type the anonymous delegate multiple times.

I've tried this, but that gives me an error:

$("#<%=txtReceiverEmailEcard1.ClientID  %>").blur(blurWatermark($(this), 'Your email address'));

Upvotes: 2

Views: 2548

Answers (3)

Tx3
Tx3

Reputation: 6916

This is from the jQuery API documentation

More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

And the signature of the method is

.each( function(index, Element) )

function(index, Element)A function to execute for each matched element.

You can then write

$('.menu a').each(myFunction)

function myFunction(index, Element) { 
    alert(this); /* this points to the element */
}

That basically means that you can get all kind of nice information (like index) to your callback.

Upvotes: 6

Shadikka
Shadikka

Reputation: 4276

Simply:

$('.menu a').each(doAnimate)

Wherever an anonymous function works, a reference to a "normal" one works just as well. :) Then you need to use the function parameters like

function doAnimate (index, elem) {
    $(elem).animate({paddingLeft: $(elem).width()}, 200);
}

Upvotes: 2

rahul
rahul

Reputation: 187030

You can try something like

$('.menu a').each(function(){
    doAnimate($(this));
});

If its a reusable one then develop a plugin that you can easily associate with jQuery objects.

Upvotes: 1

Related Questions