Don Sky Don Sky - 4 months ago 14
jQuery Question

Stopping jquery process

I have one div hidden out of page and one part is visible like:

div{
left: -100px;
width: 150px;
height: 50px;
}


I used jquery to show whole div:

$("div").hover(function(){
$("div").animate({left: '0px'});
},function(){
$("div").animate({left: '-100px'});
});


When I
hover
over the div and quickly
unhover
over it multiple times, It seems to play the animation the same amount of times I do this. How can I make it stop mid-animation if I stop hovering over the div, and how can I make the animation start only after I have hovered over it for a certain amount of time.

Answer

You can use .stop() to stop the previous animation.

$("div").hover(function() {
  $("div").stop().animate({
    left: '0px'
  }, "slow");
}, function() {
  $("div").stop().animate({
    left: '-100px'
  });
}, "slow");
div {
  left: -100px;
  width: 150px;
  height: 50px;
  background-color: blue;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div></div>

If you want it to wait until you've been hovering for a bit before the animation starts, you can use setTimeout, and you can cancel the timeout in the unhover function.

var hoverTimer;
$("div").hover(function() {
  hoverTimer = setTimeout(function() {
    $("div").stop().animate({
      left: '0px'
    }, "slow");
  }, 1000);
}, function() {
  clearTimeout(hoverTimer);
  $("div").stop().animate({
    left: '-100px'
  });
}, "slow");
div {
  left: -100px;
  width: 150px;
  height: 50px;
  background-color: blue;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div></div>

Comments