Soft internal scroll with jQuery

From snippet wiki
Jump to navigation Jump to search

Jumping to content on the current page is done by linking to an internal anchor via '#someid'.

As this makes a harsh jump and even scrolls to tight at the top, you can use that jQuery function:

$('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top-50
        }, 1000);
        return false;
      }
    }
});

In this example it scrolls soft downwards and leaves 50 pixel space on top of the target.