0

In my plugin I handle animations externally,and they are fired only in some events.

ex:

var animateToLeft = function() {
    $elements.animate({
        marginLeft: '+=' + 300,
        marginRight: '-=' + 300
    });
},
    animateToRight = function() {
        $elements.animate({
            marginLeft: '-=' + 300,
            marginRight: '+=' + 300
        });
    };

Later in my plugin I have to check if an option is true or false and then apply the animations:

if( true === options ) {
    $button.click( animateToRight );
} else {
    $button.click( animateToLeft );
}

Thus far the code works just fine. but I need to add two more callback functions according to the if-else statement

var callback1 = function() {
    //do something
},
    callback2 = function() {
    //do something else
    }

I cannot add callback functions to the animations directly I need to add them during the if-else statement. I tried this way but it didn't worked:

if( true === options ) {
    $button.click( animateToRight, function() {
        $body.bind( callback1 );
    });
} else {
    $button.click( animateToLeft, function() {
        $body.bind( callback2 );
    });
}

How can I add those callbacks? Is there a simpler way maybe?

1 Answer 1

2

You could pass the callback to the animate function which will be called once the animation is complete.

// Allow animate functions to be passed a callback
var animateToLeft = function (callback)
{
    $elements.animate({
        marginLeft: '+=' + 300,
        marginRight: '-=' + 300
    }, callback);
},
animateToRight = function (callback)
{
    $elements.animate({
        marginLeft: '-=' + 300,
        marginRight: '+=' + 300
    }, callback);
};

var callback1 = function(){};
var callback2 = function(){};

if( true === options )
{
    $button.on('click', function()
    {
        // when button is clicked call animate with the callback.
        animateToRight(callback1)
    });
} 
else
{
    $button.on('click', function()
    {
        animateToRight(callback2)
    });
}

DEMO

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

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.