Search code examples
jqueryscrolloffsetsmoothing

Smooth page scrolling offset dependent on element height


Using a smooth page scroll to navigate between sections of a one page site. Need help finding a way to make the element not scroll to the very top, but instead to an offset distance as defined by the height of a certain page element (in this case, ‘nav’). I found a solution using a static number but this won’t cut it as the fixed nav bar’s height will change at various breakpoints. So in the fiddle example below, if the screen is <400px wide the offset will grab the nav's height of 50px and use that... and if the screen is 400px+ it will use 100px. Is this possible?

$('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
    }, 1000);
    return false;
  }
}
});

fiddle: http://jsfiddle.net/pixeloco/b3Lrdmam/


Solution

  • Just do this :

    scrollTop: target.offset().top - $('nav').height()
    

    Demo