Scrolling to an internal hash link

Another little JS trick I wanted to bookmark for my own benefit.

The problem: You have a page filled with internal hash links, but don’t like the way the page jumps to the new location when you click one. You’d like it to scroll smoothly instead.

The solution: Use JavaScript/jQuery to cancel the default click event and scroll to the desired location instead.

$('a[href^=#]').on('click', function(e) { // apply to all hash links
  var el = $(this).attr('href');          // get the href
  e.preventDefault();                     // cancel default action
  $('body').animate({
      scrollTop: $(el).position().top     // scroll to the ID
    }, function() {
      window.location.hash = el;          //change bookmarkable URL
  });
});

jsBin demo

Leave a Reply

Your email address will not be published. Required fields are marked *

*