2

I have this snippet of Jquery for smooth scrolling to an anchor:

<li><a href="#home">Home</a></li>

to take you to...

<a name="home"></a>

.

var $root = $('html, body');
$('a').click(function() {
var href = $.attr(this, 'href');
$root.stop().animate({
    scrollTop: $(href).offset().top
}, 500, function () {
    window.location.hash = href;
});
return false;
});

it works great but is there a way to stop the animation if you scroll again, right now this has to finish the 500ms and goes jittery when try to scroll whilst it animates...

Any help would be great, thanks!

Olly F
  • 255
  • 5
  • 17

1 Answers1

2

This should work. Credit to @TomBates from his answer to let user scrolling stop jquery animation of scrolltop?

var $root = $('html, body');

$('a').click(function() {
  var href = $.attr(this, 'href');

  $root.stop().animate({
    scrollTop: $(href).offset().top
  }, 500, function() {
    window.location.hash = href;
  });

  return false;
});

$root.bind('scroll mousedown DOMMouseScroll mousewheel keyup touchstart', function(e) {
  if (e.which > 0 || e.type === 'mousedown' || e.type === 'mousewheel' || e.type === 'touchstart') {
    $root.stop();
  }
});
.home, .footer {
    width: 100%;
    height: 600px;
}

.home {
    background-color: #0FF;
}

.footer {
    background-color: #FF0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="home">
    <a id="home"></a>
</div>
<div class="footer">
    <a href="#home">Home</a>
</div>
Community
  • 1
  • 1
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • After the code you provided, in a context where ``$root`` is defined. – Patrick Roberts May 13 '15 at 06:50
  • so like var $root = $('html, body'); $('a').click(function() { var href = $.attr(this, 'href'); $root.stop().animate({ scrollTop: $(href).offset().top }, 10000, function () { window.location.hash = href; }); return false; }); $(window).scroll(function() { $root.stop(); }); ? Sorry jquery novice :) – Olly F May 13 '15 at 06:53
  • @OllyF Please provide the relevant HTML in your question, otherwise there's no way I can tell whether it works or not. – Patrick Roberts May 13 '15 at 06:59