ZACK BRADY

Using jQuery to Create Scrolling Navigation on a Single Page

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


jQuery, Web Design and Development
jquery
  • Klaus-dieter Michel

    Thanks for this.

    There’s a problem with your codepen example. For the first two divisions you use e.g. div class=”one”, for the last two e.g. div id=”three”. This is inconsistent and clicking ‘one’ and ‘two’ subsequently does not work.

    For my part I nicked this example http://css-tricks.com/examples/SmoothPageScroll. It works great.

    Interesting of course is your thing with stopping the page from refreshing with ‘return false’.

  • Klaus-dieter Michel

    I have to revise what I’ve written below.

    The mentioned css-tricks jQuery script wanted to be too clever and on an page with a number of external links, not related to the page scrolling behaviour, it passed out. So I basically used the script introduced here, much more simple and straightforward, and it works like a charm.