Writing jQuery functions that allow chaining.

Posted by Rich Bradshaw on Stack Overflow See other posts from Stack Overflow or by Rich Bradshaw
Published on 2011-01-10T21:52:15Z Indexed on 2011/01/10 21:53 UTC
Read the original article Hit count: 169

Filed under:

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?

© Stack Overflow or respective owner

Related posts about jQuery