Tweet
Reader Klaus-dieter Michel recently asked:
Do you know how it is done to have a link within a page and when clicked the page scrolls down (vertically animated) towards the link target? Like the right hand sidebar menu on this page: http://stackoverflow.com/editi… Is that jQuery?
Yes, yes it is jQuery. A nice and simple bit of jQuery. I’ve whipped up a quick example of what he was talking about on CodePen.
Check out this Pen!
The key is to first treat your markup as if you creating a standard “link to section” navigation. Enter the id of the element you want to jump to in the href
attribute.
The fun part is of course done through javascript/jQuery.
$('.nav a').click(
function(){
var target = $(this).attr('href');
var targetLoc = $(target).offset().top;
$('html, body').stop().animate({scrollTop : targetLoc}, 1000);
return false;
});
This code uses jQuery’s .click()
function to pick up when one of the navigation buttons have been clicked. We then get the href
attribute from that anchor tag and use it to find the target id’s location from the top of the document. We use the animate library to create the smooth scrolling animation. Finally we need to stop the page from refreshing and we can accomplish that with return false