Skip to content Skip to sidebar Skip to footer

How Do I Make The Navigation Bar Of My Site Stay At The Top When The Viewer Scrolls?

I am working on my website, and I want to have the the navigation bar stay at the top of the page when the user scrolls down. The main problem is that I want the header (appears ab

Solution 1:

There is a jQuery plugin that does it for you. It's called sticky. The official website here : http://stickyjs.com/

And the code here:

<script src="jquery.js"></script>
<script src="jquery.sticky.js"></script>
<script>
    $(document).ready(function(){
        $("#sticker").sticky({topSpacing:0});
    });
</script>

Hope this helps


Solution 2:

You need to compare the offset().top of the element to the windows' current scrollTop. Try this:

var timer;
$(window).scroll(function() {
    var $div = $('#div');
    clearTimeout(timer);
    timer = setTimeout(function() {
        if ($div.offset().top < $(this).scrollTop()) {
            $div.addClass('fixed');
        }
        else {
            $div.removeClass('fixed');
        }
    }, 250);
});

Example fiddle

Note the scroll function fires once for every pixel scrolled, so the timer is there for performance reasons.


Post a Comment for "How Do I Make The Navigation Bar Of My Site Stay At The Top When The Viewer Scrolls?"