Search code examples
jqueryjquery-animatecss-transitionsjquery-transit

jQuery Stop Only Animations Being Set


Say I have this.

var e = $('#div');

I want to do

e.fadeOut(3000).animate({'top':500}, 3000);

And then

e.animate({'top':250}, 3000);

Immediately, stopping the original top animation on e, but without stopping the fade.

Note I am also using the jQuery Transit plugin in place of jQuery animate.


Solution

  • You can run the fade animation with the queue option false. The first button starts both animations and the second button overrides just the top animation.

    I think there is another way of doing it using a named queue but I find it more lengthy because you have to manually start the animation with .dequeue('queueName')

    $(function(){
    	var $div = $('#myDiv');
    	var $btnStart = $('#btnStart');
    	var $btnEnd = $('#btnEnd');
    
    
    	$btnStart.click(function(){
    		$div.animate({'top':'500px'}, 3000);
    		$div.animate({opacity: 0}, {duration: 5000, queue: false});
    	});
    	$btnEnd.click(function(){
    		$div.animate({'top':0}, {duration: 3000, queue: false});
    	});
    });
    #myDiv{
    	background:red;
    	height:20px;
    	width:20px;
    	position:absolute;
    	top:100px;
    	left:100px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="btnStart">Start</button>
    <button id="btnEnd">End</button>
    <div id="myDiv">
    </div>

    EDIT:

    Just noticed you mentioned not wanting to use queue:false. Below it's the same thing using queue names and stopping individual animations.

    $(function(){
    	var $div = $('#myDiv');
    	var $btnStart = $('#btnStart');
    	var $btnEnd = $('#btnEnd');
    
    	$btnStart.click(function(){
    		$div.animate({'top':'500px'}, {duration: 3000, queue:'top'});
    		$div.dequeue('top');
    		$div.fadeOut(5000);
    	});
    	$btnEnd.click(function(){
    		$div.stop('top').animate({'top':0}, {duration: 3000, queue: 'top'});
    		$div.dequeue('top');
    	});
    });
    #myDiv{
    	background:red;
    	height:20px;
    	width:20px;
    	position:absolute;
    	top:100px;
    	left:100px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="btnStart">Start</button>
    <button id="btnEnd">End</button>
    <div id="myDiv">
    </div>