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?
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).