jQuery Stop Only Animations Being Set

200 Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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>

0
On

Try

var e = $("#div");

$("button").on("click", function() {
  if (!e.is(":animated")) {
      e.animate({"top":"+=500", "opacity":0}, 3000, "linear")
  }
  else {
      e.stop(true, false).animate({"top": "-=250", "opacity":0}, 3000, "linear")
  };  
});
#div {
  position:relative;
  top:0px;
  font-size:36px;
  border:2px solid green;
  background:orange;
  height:54px;
  width:54px;
  text-align:center;
}

button {
  width:54px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<button>click</button>
<div id="div"></div>