Stop jquery animation?

Hi, I have this:

  $(function() {
    $('a[href*=#]:not([href=#])').click(function() {
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top - 79
          }, 1500, 'easeOutExpo');
          return false;
        }
      }
    });
  });

And if I click an anchor and then start scrolling my mousewheel before the 1500ms animation is done I get this ugly stuttering, like if the animation is clashing with my scrolling, dunno how to explain. Is it possible to edit this code so that the animation cancels if i scroll?

You could try the stop() method, which stops the currently-running animation on the matched elements.

HI,

There probably is a much better answer this but how about adding a class to the html element before scrolling takes place and then removing it when the animation is finished.

e.g.

.noscroll,.noscroll body{
    overflow:hidden;
}

Then the middle bit of the scrip looks like:

 $('html').addClass('noscroll');
   $('html,body').animate({
     scrollTop: target.offset().top - 79
   }, 1500,function() {
     // Animation complete.
     $('html').removeClass('noscroll'); 
   });

The main problem is that the scrollbar vanishes during the scroll and also assumes you aren’t doing other clever things with html body.

I’m sure one of the JS experts has a better method to detect mouse-wheel scroll and ignore it for the duration of the animation though.

Might be doable with a combination of scroll() and :animated
E.g.

$(window).on("scroll touchmove mousewheel", function(e){
  if( $(elem).is(':animated') ) {
    e.preventDefault();
    e.stopPropagation();
    return false;
  }
});
1 Like

Yeah I was thinking about this one to… problem is I don’t know where to use this method on my current code, I tried: putting .stop() before click() and animate(), didnt change anything tho.

Can you provide a demo that reproduces your problem?

http://jsfiddle.net/whp8ce26/3/ try scrolling with your mousewheel before the 1500ms animation is finished.

Here you go:

$('a').on("click", function(e) {
  var target = $(this.hash);
  $('html,body').animate({scrollTop: target.offset().top - 79}, 5500, 'easeOutExpo');
  e.preventDefault();
});

$(window).on("mousewheel", function(){
  $('html,body').stop();  
});

Demo

1 Like

thanks dude!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.