Search code examples
javascriptjqueryhtmlcssmenubar

moving menu bar with javascript


I am designing a site with a menu bar that starts with a relative position in a header element. Its distance from the top in pixels is 300. I want to make a javascript function that changes the position to fixed and the top to 0 when i scroll on the page below 300 pixels. This is so that the menu bar will always be at the top of the screen when navigating down. Does anyone have a good method of doing this? I thought of maybe doing some type of function that checks after a set timer for like 10 ms and checking the window.pageYoffset. This cant be the best method. Any suggestions are appreciated.


Solution

  • Monitor the window's scroll event:

    $(window).on('scroll', function(e) {
        if ($('body').scrollTop()>300) {
            $('#header').css('position','fixed');
        } else {
            $('#header').css('position','relative');
        }
    });
    

    Slightly optimized:

    $(window).on('scroll', function(e) {
        $('#header').css('position', ($('body').scrollTop()>300) ? 'fixed' : 'relative');
        }
    });