Search code examples
jquerysmooth-scrolling

How to fix "Smooth Scrolling" with fixed navigation


Once I set up my smooth scrolling along with my fixed navigation, I can't get the anchor to stop with the added 100px above. It jumps back to the original hash.

I've tried setting the offset to 100, but no luck with the jumping. It works fine on Safari, but not on Chrome or Firefox.

Here's that I've used:

// URL updates and the element focus is maintained
// originally found via in Update 3 on http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links

// filter handling for a /dir/ OR /indexordefault.page
function filterPath(string) {
  return string
    .replace(/^\//, '')
    .replace(/(index|default).[a-zA-Z]{3,4}$/, '')
    .replace(/\/$/, '');
}

var locationPath = filterPath(location.pathname);
$('a[href*="#"]').each(function () {
  var thisPath = filterPath(this.pathname) || locationPath;
  var hash = this.hash;
  if ($("#" + hash.replace(/#/, '')).length) {
    if (locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/, '')) {
      var $target = $(hash), target = this.hash;
      if (target) {
        $(this).click(function (event) {
          event.preventDefault();
          $('html, body').animate({scrollTop: $target.offset().top - 100}, 1000, function () {
            location.hash = target; 
            $target.focus();
            if ($target.is(":focus")){ //checking if the target was focused
              return false;
            }else{
              $target.attr('tabindex','-1'); //Adding tabindex for elements not focusable
              $target.focus(); //Setting focus
            };
          });       
        });
      }
    }
  }
});

Here is my dev link: http://dev.savagebrands.com

I'd like the anchors to be 100px above the actual section it is linking to.


Solution

  • Try to always return false in the end of your click function. That will prevent the default browser behaviour

    $(this).click(function (event) {
        event.preventDefault();
        // Your code
        return false;
    });