2

I want to write some code that allows me to replace jQuery's animate function with one that does different things, but still allows me to call a secondary function on completion.

At the moment, I'm writing lots of code like this;

if (cssTransitions) {
   $("#content_box").css("height",0);

   window.setTimeout(function() {
       secondFunction(); 
   }, 600);
} else {
    $("#content_box").animate({
        height:0
    }, 600, function() {                
        secondFunction();
    });
}

I'd much rather write a function that looks like this:

function slideUpContent(object) {
    if (cssTransitions) {
         object.css("height",0);
         // Not sure how I get a callback here
    } else {
        $("#content_box").animate({
            height:0
        }, 600, function() {
        });
    }
}

That I could use like this:

slideUpContent("#content_box", function(){
    secondFunction();
});

But I'm not sure how to get the functionality I need - namely a way to run another function once my one has completed.

Can anyone help my rather addled brain?

1

3 Answers 3

3

The functionality you are looking for is called a callback.

It is simple enough to implement. Just pass the anonymous function (or other function) as a parameter, then call the variable passed in by appending brackets callback() (obviously checking to see if it is a valid function first).

function slideUpContent(object, callback) {
    if (cssTransitions) {
         object.css("height",0);
         // Perform callback if set
         if ($.isFunction(callback)) {
             callback();
         }
    } else {
        $("#content_box").animate({
            height:0
        }, 600, callback);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

That's really obvious now I see it! Thanks!
Actually, one question – does this work even if no callback is specified?
@Rich Bradshaw, should do. The use of callback passing to animate() should be fine, depends what it wants as a default.
1

Chaining usually means returning this so you can do

$("selector").function1().function2();

For your example, you just need

function1(param1, f) {
    // do stuff
    f();
 }

then call it with

function1("parameter", function2);

Comments

0

I had recently created a sequence opening animation for a website. I found this website to be a good source of information. The part that might be helpful for you is the section titled, "Creating a sequence of animations".

http://www.elated.com/articles/super-easy-animated-effects-with-jquery/

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.