Skip to content
Advertisement

Chain to pre defined functions with jQuery

I have been trying to chain this last bit of code to work nicely.

It calls two functions that have been preset:

slideToImage(newIndex);
setCaption();

I want the caption to be set once the image has slid.

This has always been a confusing topic for me as I have tried different ways of calling it such as:

callbacks = $.Callbacks();
            
callbacks.add(slideToImage(newIndex));
callbacks.add(setCaption());
callbacks.fire();

But that does not work.

Advertisement

Answer

slideToImage must contain some animation logic that happens over time. So slideToImage would start the animation process and then return before the animation has completed which causes setCaption to be called to early.

You should pass setCaption into slideToImage as a callback and call it once the animation has completed.

function slideToImage(newIndex, callback) {
    // I assume you're using jQuery for animation
    targetElement.animate({left: 100}, 200, function() {
        // once animation has finished we call the callback function
        callback();
    });
}

slideToImage(newIndex, function() {
    setCaption();
});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement