div that does not exceed certain limits

4

Well, in this link :: link there is a menu that when loading the page is not fixed at the top of the screen, however When you scroll down the page a little, this menu appears and is fixed at the top. How do you do that?

    
asked by anonymous 05.09.2014 / 03:36

1 answer

4

Example online at jsfiddle . I made an example as clean as possible to allow adaptation.

HTML

<div class="div1"></div>

<div id="nav">
    <ul>
        <li><a href="#">Link A</a></li>
        <li><a href="#">Link B</a></li>
        <li><a href="#">Link C</a></li>
        <li><a href="#">Link D</a></li>
    </ul>
</div>

<div class="div2"></div>

JS

$(function() {
    var offsetTop = $('#nav').offset().top;
    var navigation = function(){
        var scrollTop = $(window).scrollTop();

        if (scrollTop > offsetTop){
            $('#nav').css({ 'position': 'fixed', 'top':0, 'left':0 });
        }else{
            $('#nav').css({ 'position': 'relative' }); 
        }   
    };

    $(window).scroll(function(){
        navigation();
    });
});

CSS

*{margin:0; border:0; padding:0; font:12px Arial, Helvetica, sans-serif}
.div1{background:#669900; height:200px; width:100%}
.div2{background:#669900; height:700px; width:100%}

#nav{width:100%; height:50px; background:#fff;}
#nav ul{list-style:none; margin:0; padding:5px;}
#nav ul li{ margin:0; padding:0; display:inline; }
#nav ul li a{float:left; margin:0 5px; padding:0 10px; height:40px; line-height:40px; color:#fff; background:#333; text-decoration:none}
    
05.09.2014 / 04:39