Scroll to an ID with jQuery

It is always nice to add a scrolling effect for links that point to an ID on the same HTML page – and it is really easy to do with a few lines of code if you are already using jQuery.


First, we need to add the scroll function:

<script type="text/javascript">
function scrollToId(id, scroll_offset) {
	$('html,body').animate({scrollTop: $("#"+id).offset().top - scroll_offset},'slow');
};
</script>

Next, you need to modify your links from something like this:

 <a href="#footer">Footer</a>

To be more like this:

 <a href="javascript://" onclick="scrollToId('#footer');">Footer</a>

The second parameter of the function (scroll_offset) can be used to fine-tune the exact position where the link will scroll. This is useful as sometimes if you scroll to a headline, some of the headline text might not be fully visible.

Auto-scroll links to IDs

There is, of course, an even simpler solution if you don’t need different scroll offsets on your page. This code will auto-convert your links to IDs, so you don’t even have to modify your code, just insert this somewhere:

<script type="text/javascript">
$("document").ready(function() {
  $('a[href^="#"]').click(function(event) {
    var target = $( $(this).attr('href') );
    if( target.length ) {
      event.preventDefault();
      $('html, body').animate({
        scrollTop: target.offset().top
      }, 1000);
    }
  });
});
</script>