Search code examples
jquerycssfixedsticky

jQuery scrolling to div on css change (sticky nav)


I'm using my own code below to try and set a sticky nav.

Its working, but whenever it changes the div to fixed, the browser automatically scrolls to it. This means the browser cannot scroll any further than where the original nav bar is.

Any ideas?

$(document).ready(function() {
    var stickNavOffset = $('#nav').offset().top;

    function sticky() {
        if ($(this).scrollTop() > stickNavOffset-1) {
            $('#nav').css({position:'fixed',left:'auto'});
        } else {
            $('#nav').css({position:'relative',left:'auto'});
        }
    }

    $(window).scroll(function() {
        sticky();
    });
});

Solution

  • Your problem happens when your content is just the right height that when your sticky element is set to position: relative, it's high enough to vertically scroll, and when removed from the document flow, the content is no longer high enough to force scrolling.

    So when it switches to fixed, you snap back to the top because your document's not tall enough to scroll, which sets your sticky element to position: relative again, which brings back the scroll bar.

    You can test this by just adding more content to your page - if it's tall enough that even without the sticky element, it'll still scroll, you won't have this problem.

    You should notice another problem, though, which is that your content jumps a little bit. Actually, it jumps exactly the height of your sticky element, which is suddenly no longer there.

    That's what I meant in my comment when I said you'd have to account for that space with your code. In the past, when I've created sticky elements, I create a cloned placeholder element that I leave set to position: relative that I leave in place so that the height doesn't jump.