Reputation: 6674
I am using some code from www.css-tricks.com that can be used to animate local scrolling to a page anchor. Here is the code snippet:
$("class-name-here").on("click", function() {
var $target = $(this.hash);
$target = $target.length && $target
|| $('[name=' + this.hash.slice(1) +']');
if ($target.length) {
var targetOffset = $target.offset().top;
$('html,body')
.animate({scrollTop: targetOffset}, 1500, "easeOutQuint");
return false;
}
});
I have tried using a variety of times for the animation duration, but when I click the link, the page does scroll correctly, but after the scroll reaches the destination, the animation continues. In other words, it scrolls, but after the animation seems complete, if you try to scroll away manually, the page animates itself to that location again for about half a second.
Is there something wrong with the snippet / has anyone seen this before?
Upvotes: 0
Views: 134
Reputation: 1720
I found an example where we stop the scroll-event on different kind of events. I made an example for you without using jquery-ui. The scroll-timer is set to 2.5 sec so that you can stop it anytime before it reaches its target: JS-FIDDLE
function goTo(sectionID) {
var page = $("html, body");
page.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
page.stop();
});
page.animate({ scrollTop: $("#section" + sectionID).offset().top }, 2500, 'swing', function(){
page.off("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove");
});
return false;
};
Upvotes: 1
Reputation: 931
Can you try this :
$('.your-class-name-here').click(function(event) {
var id = $(this).attr("href");
var offset = 10;
var target = $(id).offset().top - offset;
$('html, body').animate({scrollTop:target}, 1000);
event.preventDefault();
});
});
Upvotes: 0