Search code examples
jquerynavbarsticky

jQuery sticky navbar


I am trying to make a sticky navbar that sticks to the top only when it touches the top, but my jQuery code is not working.

Code(jQuery):

function findDistance()
{
    var distToTop = $(window).scrollTop();
    var navOffset = $('#navbar').offset().top;
    var distance = (navOffset - distToTop);
    return distance;
}
$(document).ready(function()
{
    var defaultNavDist = 166;
    var distance = findDistance();
    var fixedSet = false;
    $(window).scroll(function()
    {
        if(distance < 1 && fixedSet == false)
        {
            fixedSet = true;
            $('#navbar').css('position', 'fixed');
        }
    });
});

Link to jsFiddle: http://jsfiddle.net/fj10ruqs/


Solution

  • When the window scroll handler runs, distance is not being recalculated. You need to put distance = findDistance(); inside the scroll handler. You'll also probably want to add $('#navbar').css('top', '0'); when you are fixing it to the top so that it will be at the top.

     $(window).scroll(function()
        {
            distance = findDistance();
            if(distance < 1 && fixedSet == false)
            {
                fixedSet = true;
                $('#navbar').css('position', 'fixed');
                $('#navbar').css('top', '0');
            }
        });