March 5, 2012

jQuery Animation Conditional w/a Callback Function

Question by Andaero

EDIT BELLOW

How do I code the #west animation call on the #contentBox animation when it completes?

Basically I have a toggle button that animates/changes a div’s css and then to another div’s css once/after the first animation completes; then reverses the next time the toggle is executed.

Any help is appreciated. Thank-you.

The Conditional Statements:

$("#menuToggle").click(
    function() {

        var $west = $("#west");
        var $contentBox = $("#contentBox");

        $contentBox.animate({
                marginLeft : parseInt($contentBox
                        .css('marginLeft'), 10) == -320
                        ? $contentBox.outerWidth()
                        : -320
        });

        $west.animate({
            left : parseInt($west
                .css("left"), 10) == 0 
                ? -$west.outerWidth() 
                : 0
        });
   });

I went to the old fashoned way with out shorthanding the conditional statement

Answer by Andaero

I re-wrote the statement so it wasnt in shorthand and it works fine.

$("#menuToggle").click(

        function() {
            //var n = $("#west");
            var position = $("#west").offset();

            if (position.left == "0") {
                $("#west").animate({"left" : "-=300px"}, "slow")
                .animate({"width" : "1%"}, "fast", 
                    function() {
                    $("#contentBox").animate({"width" : "98%"}, "normal");
                });
            } else {
                $("#contentBox").animate({"width" : "70%"}, "normal", 
                    function() {
                    $("#west").animate({"width" : "30%"}, "fast")
                    .animate({"left" : "+=300px"}, "slow");
                });
            }
        });

Answer by Starx

You can always pass a callback function to the animate() method, which execuies once the animation is complete.

$("#menuToggle").click(
    function() {

        var $west = $("#west");
        var $contentBox = $("#contentBox");

        $contentBox.animate({
                marginLeft : parseInt($contentBox
                        .css('marginLeft'), 10) == -320
                        ? $contentBox.outerWidth()
                        : -320
        }, 5000, function() {
             //this is the callback part
            $west.animate({
                left : parseInt($west
                    .css("left"), 10) == 0 
                    ? -$west.outerWidth() 
                    : 0
            });
        });

   });

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!