javascript - Smooth scrolling when clicking an anchor link -
i have couple of hyperlinks on page. faq users read when visit section.
using anchor links, can make page scroll towards anchor , guide users there.
is there way make scrolling smooth?
but notice he's using custom javascript library. maybe jquery offers somethings baked in?
$(document).on('click', 'a[href^="#"]', function (event) { event.preventdefault(); $('html, body').animate({ scrolltop: $($.attr(this, 'href')).offset().top }, 500); });
and here's fiddle: http://jsfiddle.net/9sdlw/
if target element not have id, , you're linking name
, use this:
$('a[href^="#"]').click(function () { $('html, body').animate({ scrolltop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top }, 500); return false; });
for increased performance, should cache $('html, body')
selector, doesn't run every single time anchor clicked:
var $root = $('html, body'); $('a[href^="#"]').click(function () { $root.animate({ scrolltop: $( $.attr(this, 'href') ).offset().top }, 500); return false; });
if want url updated, within animate
callback:
var $root = $('html, body'); $('a[href^="#"]').click(function() { var href = $.attr(this, 'href'); $root.animate({ scrolltop: $(href).offset().top }, 500, function () { window.location.hash = href; }); return false; });
Comments
Post a Comment