[jquery] Leave menu bar fixed on top when scrolled

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.

This question is related to jquery css

The answer is


You can try this with your nav div:

postion: fixed;
top: 0;
width: 100%;

This is jquery code which is used to fixed the div when it touch a top of browser hope it will help a lot.

<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$(function() {
    $.fn.scrollBottom = function() {
        return $(document).height() - this.scrollTop() - this.height();
    };

    var $el = $('#sidebar>div');
    var $window = $(window);
    var top = $el.parent().position().top;

    $window.bind("scroll resize", function() {
        var gap = $window.height() - $el.height() - 10;
        var visibleFoot = 172 - $window.scrollBottom();
        var scrollTop = $window.scrollTop()

        if (scrollTop < top + 10) {
            $el.css({
                top: (top - scrollTop) + "px",
                bottom: "auto"
            });
        } else if (visibleFoot > gap) {
            $el.css({
                top: "auto",
                bottom: visibleFoot + "px"
            });
        } else {
            $el.css({
                top: 0,
                bottom: "auto"
            });
        }
    }).scroll();
});
});//]]>  

</script>

You can also use css rules:

position: fixed ; and top: 0px ;

on your menu tag.


check the link below, it has the html, css, JS and a live demo :) enjoy

http://codepen.io/senff/pen/ayGvD

_x000D_
_x000D_
// Create a clone of the menu, right next to original._x000D_
$('.menu').addClass('original').clone().insertAfter('.menu').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeClass('original').hide();_x000D_
_x000D_
scrollIntervalID = setInterval(stickIt, 10);_x000D_
_x000D_
_x000D_
function stickIt() {_x000D_
_x000D_
  var orgElementPos = $('.original').offset();_x000D_
  orgElementTop = orgElementPos.top;               _x000D_
_x000D_
  if ($(window).scrollTop() >= (orgElementTop)) {_x000D_
    // scrolled past the original position; now only show the cloned, sticky element._x000D_
_x000D_
    // Cloned element should always have same left position and width as original element.     _x000D_
    orgElement = $('.original');_x000D_
    coordsOrgElement = orgElement.offset();_x000D_
    leftOrgElement = coordsOrgElement.left;  _x000D_
    widthOrgElement = orgElement.css('width');_x000D_
_x000D_
    $('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement+'px').show();_x000D_
    $('.original').css('visibility','hidden');_x000D_
  } else {_x000D_
    // not scrolled past the menu; only show the original menu._x000D_
    $('.cloned').hide();_x000D_
    $('.original').css('visibility','visible');_x000D_
  }_x000D_
}
_x000D_
* {font-family:arial; margin:0; padding:0;}_x000D_
.logo {font-size:40px; font-weight:bold;color:#00a; font-style:italic;}_x000D_
.intro {color:#777; font-style:italic; margin:10px 0;}_x000D_
.menu {background:#00a; color:#fff; height:40px; line-height:40px;letter-spacing:1px; width:100%;}_x000D_
.content {margin-top:10px;}_x000D_
.menu-padding {padding-top:40px;}_x000D_
.content {padding:10px;}_x000D_
.content p {margin-bottom:20px;}
_x000D_
<div class="intro">Some tagline goes here</div>
_x000D_
_x000D_
_x000D_


$(window).scroll(function () {

        var ControlDivTop = $('#cs_controlDivFix');

        $(window).scroll(function () {
            if ($(this).scrollTop() > 50) {
               ControlDivTop.stop().animate({ 'top': ($(this).scrollTop() - 62) + "px" }, 600);
            } else {
              ControlDivTop.stop().animate({ 'top': ($(this).scrollTop()) + "px" },600);
            }
        });
    });

Or do this in more dynamic way

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

In CSS add class

.fixed {
    position: fixed;
    top: 0;
}

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/


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");
        }
    });
});

you may want to add:

 $(window).trigger('scroll') 

to trigger the scroll event when you reload an already scrolled page. Otherwise you might get your menu out of position.

$(document).ready(function(){
        $(window).trigger('scroll');
        $(window).bind('scroll', function () {
            var pixels = 600; //number of pixels before modifying styles
            if ($(window).scrollTop() > pixels) {
                $('header').addClass('fixed');
            } else {
                $('header').removeClass('fixed');
            }
        }); 
}); 

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');
         }
    });

try with sticky jquery plugin

https://github.com/garand/sticky

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