Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create a Sticky Menu bar with CSS and Jquery

    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.34k
    Comment on it

    In this example, we will create a simple webpage that consists of the header, the navigation and the content.

    <div class="wrapper">  
        <div class="header">  
            Header  
        </div>  
        <div class="nav">  
            Navigation  
        </div>  
        <div class="content">  
            <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum <br><br></p>  
        </div>  
    </div>
    

    And, we will apply the sticky position to the navigation.

    But first, we will define the styles in the stylesheet, like so.

    body {
        margin: 45px 0 0;
        padding: 0;
        font-family:Arial, Helvetica, sans-serif;
        font-size:12px;
    }
    .header, .nav {
        color: #FFFFFF;
        text-align: center;
    }
    .header {
        background-color: #333333;
        padding: 50px 0;
    }
    
    .content {
        margin: 10px auto 100px;
        width: 600px;
    }
    .sticky {  
        position: fixed;  
        width: 100%;  
        left: 0;  
        top: 0;  
        z-index: 100;  
        border-top: 0;  
    } 
    

    Then, we will apply that class to the navigation conditionally with jQuery.

    $(document).ready(function() {  
        var stickyNavTop = $('.nav').offset().top;  
    
        var stickyNav = function(){  
        var scrollTop = $(window).scrollTop();
    
            if (scrollTop > stickyNavTop) {   
                $('.nav').addClass('sticky');  
            } else {  
            $('.nav').removeClass('sticky');   
            }  
        };  
    
        stickyNav();  
    
        $(window).scroll(function() {  
            stickyNav();  
        });  
    
    });  
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: