Steve
Steve

Reputation: 55615

JQuery Animate Complete Callback called Multiple Times

This is difficult to explain, so I've included a code example below, and a jsFiddle link to demonstrate the issue.

Here goes...I have the following code, where I am creating one JS object that has methods to control some JQuery (1.6.4) based animation. If I start both the parent and child animations, then in the parent complete callback I stop the child, the parent complete functions gets called multiple times. However, if I pull those methods out of an object, then I do not have this issue. Any idea why, and how to get around this while keeping everything contained within an object?

http://jsfiddle.net/um3dU/41/

HTML

<div id="parent">
    <div id="child">
       <div id="scrolling-text">  
           this is scrolling text to explain the issue I'm running into      
       </div>    
    </div>    
</div>

CSS

#parent         { position: absolute; left: 0px; top: 0px; width: 960px; height: 100px; background-color: blue; }
#child          { position: absolute; left: 0px; top: 25px; width: 400px; height: 20px; background-color: red; }
#scrolling-text { position: absolute; left: 0px; }

Javascript

var animation = {   
    startChild : function() {
        $('#scrolling-text').animate({ 
             left: -400 
        }, 
        10000, 
        function() { alert('child complete function'); });       
    },

    stopChild : function() {
        $('#scrolling-text').stop();        
    },

    startParent : function() {
        $('#parent').animate({ 
             top: 240 
        }, 
        5000, 
        $('#parent').animate({ top: 240 }, 5000, 
           function() { alert('In parent complete function'); this.stopChild(); }.bind(this));      
}      
    }
};

Calling Object Methods

animation.startChild();
animation.startParent();

Upvotes: 1

Views: 1970

Answers (1)

Doug Owings
Doug Owings

Reputation: 4448

Reference your animation variable when calling stopChild()

var animation = {
    ...
    startParent: function() {
        $('#parent').animate({ 
           top: 240 
        }, 
        5000,
        function() {
            alert('in parent complete');
            animation.stopChild();
        });
    }
}

jsfiddle

Upvotes: 1

Related Questions