jquery smooth scroll to an anchor?
Is there a way to scroll down to an anchor link using jQuery?
Like:
$(document).ready(function(){
$("#gotomyanchor").click(function(){
$.scrollSmoothTo($("#myanchor"));
});
});
?
Here is how I do it:
var hashTagActive = "";
$(".scroll").on("click touchstart" , function (event) {
if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
event.preventDefault();
//calculate destination place
var dest = 0;
if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
dest = $(document).height() - $(window).height();
} else {
dest = $(this.hash).offset().top;
}
//go to destination
$('html,body').animate({
scrollTop: dest
}, 2000, 'swing');
hashTagActive = this.hash;
}
});
Then you just need to create your anchor like this:
<a class="scroll" href="#destination1">Destination 1</a>
You can see it on my website.
A demo is also available here: http://jsfiddle.net/YtJcL/
I would use the simple code snippet from CSS-Tricks.com:
$(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
}, 1000);
return false;
}
}
});
});
Source: http://css-tricks.com/snippets/jquery/smooth-scrolling/
Best solution I have seen so far: jQuery: Smooth Scrolling Internal Anchor Links
HTML:
<a href="#comments" class="scroll">Scroll to comments</a>
Script:
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});
});