Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sticky Navigation with Smooth Scrolling is jumping

I'm having all sorts of issues with a stick nav and smooth scrolling. I just don't know enough about jQuery to troubleshoot. I'm using a smooth scrolling snippet from Chris Coyer: http://css-tricks.com/snippets/jquery/smooth-scrolling/. My page is here: http://clients.ekcetera.com/agivingchance.

Here are my problems:

  1. For any of the nav items, it scrolls partially, then jumps to the location. I'm pretty sure it's because I didn't know how to account for the sticky header, so I put the anchor up a bit to account for the height of the anchor. So, it gets to the anchor and stops, but then jumps to the proper view.
  2. When clicking the back button, it appears to not always go to the right location - sometimes it's pretty random. I'm thinking this has to do with issue 1, and hopefully it will resolve itself. I'd even be fine with removing the browser history/back button thing alltogether, but like I said, am not enough of a JQuery master to know what to remove.

Any suggestions?

Thanks in advance!

like image 521
kgarrett Avatar asked Oct 19 '12 15:10

kgarrett


1 Answers

1. Use this code from Devin Sturgeon's comment about the Smooth Scrolling post. Plus I've added a little subtraction to make up for your sticky header. Adjust to liking.

// your functions go here 
$('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 - 181
            }, 1000);
            return false;
        }
    }
});

2. Move all your anchors to the actual element you want to scroll to.

(ref: http://css-tricks.com/snippets/jquery/smooth-scrolling/#comment-197181)

like image 101
rocky Avatar answered Oct 05 '22 03:10

rocky