Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fix menu bar at top of page once header has been scrolled past

Firstly I apologise if this is too open-ended a question.

I am aware of making the header of a web page static so it is always visible at the top of the viewport and the content passes beneath it as you scroll down. This can be achieved purely with css.

I was wondering how you would achieve letting the header scroll off the page but leave a horizontal menu bar static at the top. http://www.forexfactory.com is a perfect example of this.

I see it calls a JavaScript function onHeaderComplete.execute() which I assume applies extra css style to the nav bar when the header scrolls off but I'm unsure of how it works. Any basic explanation appreciated as my JavaScript skills are relatively limited.

like image 959
harryg Avatar asked Jan 24 '13 10:01

harryg


People also ask

How do I get my menu bar to stay on top?

To create a fixed top menu, use position:fixed and top:0 . Note that the fixed menu will overlay your other content. To fix this, add a margin-top (to the content) that is equal or larger than the height of your menu.

How do you make the navigation bar stay at the top when scrolling?

Use position absolute and set the top value to the number of pixels you want the Nav bar to be from the top of the browser.

How can I make a div stick to the top of the screen once it's been scrolled to?

To make an element sticky, use the following code: make sticky('#sticky-elem-id'); When an element becomes sticky, the code maintains the remaining content's position to prevent it from jumping into the gap left by the sticky element.


2 Answers

I just answered similar question. CHECK THIS QUESTION

$(function(){
        // Check the initial Poistion of the Sticky Header
        var stickyHeaderTop = $('#stickyheader').offset().top;

        $(window).scroll(function(){
                if( $(window).scrollTop() > stickyHeaderTop ) {
                        $('#stickyheader').css({position: 'fixed', top: '0px'});
                        $('#stickyalias').css('display', 'block');
                } else {
                        $('#stickyheader').css({position: 'static', top: '0px'});
                        $('#stickyalias').css('display', 'none');
                }
        });
  });

DEMO

like image 106
Sowmya Avatar answered Oct 15 '22 06:10

Sowmya


You can write like this:

$(window).scroll(function() {
    if ($(this).scrollTop() > 50) {
         $('div').addClass('fix');
    } else {
         $('div').removeClass('fix');
    }
});

CSS

.fix{
    position:fixed;
    top:0;
    left:0;
    right:0;
    margin:0;
}

Check this http://jsfiddle.net/a42qB/

like image 36
sandeep Avatar answered Oct 15 '22 07:10

sandeep