2

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'));
1
  • Correct, 'on the fly' is anonymous function Commented Jan 14, 2011 at 9:00

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

and can i pass the $(this) also?
reason i ask is that it doesn't work right now, i've edited the question
Sorry, the function parameters need to be (index, Element) instead of just (Element), edited my answer. See api.jquery.com/each :)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.