Leave menu bar fixed on top when scrolled [closed]

I've seen some websites that when the user scrolls down the page a box would pop-up to the right or left...

Also, noticed this template: http://www.mvpthemes.com/maxmag/ the designer does a nice job leaving the nav bar fixed on top.

Now, how are these done? I guess it uses jquery to get the position of the page and to show the box.

Can you please guide me to where I can find a snippet so I can learn to do something like that.


Solution 1:

This effect is typically achieved by having some jquery logic as follows:

$(window).bind('scroll', function () {
    if ($(window).scrollTop() > 50) {
        $('.menu').addClass('fixed');
    } else {
        $('.menu').removeClass('fixed');
    }
});

This says once the window has scrolled past a certain number of vertical pixels, it adds a class to the menu that changes it's position value to "fixed".

For complete implementation details see: http://jsfiddle.net/adamb/F4BmP/

Solution 2:

In this example, you may show your menu centered.

HTML

<div id="main-menu-container">
    <div id="main-menu">
        //your menu
    </div>
</div>

CSS

.f-nav{  /* To fix main menu container */
    z-index: 9999;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
}
#main-menu-container {
    text-align: center; /* Assuming your main layout is centered */
}
#main-menu {
    display: inline-block;
    width: 1024px; /* Your menu's width */
}

JS

$("document").ready(function($){
    var nav = $('#main-menu-container');

    $(window).scroll(function () {
        if ($(this).scrollTop() > 125) {
            nav.addClass("f-nav");
        } else {
            nav.removeClass("f-nav");
        }
    });
});

Solution 3:

same as adamb but I would add a dynamic variable num

num = $('.menuFlotante').offset().top;

to get the exact offset or position inside the window to avoid finding the right position.

 $(window).bind('scroll', function() {
         if ($(window).scrollTop() > num) {
             $('.menu').addClass('fixed');
         }
         else {
             num = $('.menuFlotante').offset().top;
             $('.menu').removeClass('fixed');
         }
    });