Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Scroll Fixed Header in jQuery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 658
    Comment on it

    In this article, you will learn how to fix the header all the time while scrolling your website page. There are different jQuery plugin available for this purpose but we will use a simple jQuery based solution to make a header fixed on the top of the screen while scrolling.

    The HTML

    <html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <title>Scroll Fixed Header using JQuery</title>
    </head>
    <body>
    
    <div id="header">
        <h1>Scroll Fix Header</h1>
    </div>
    
    <p>Some text to add scrolling in page <br/><br/><br/><br/><br/></p>
    <p>Some text to add scrolling in page <br/><br/><br/><br/><br/></p>
    <p>Some text to add scrolling in page <br/><br/><br/><br/><br/></p>
    <p>Some text to add scrolling in page <br/><br/><br/><br/><br/></p>
    
    </body>
    </html>

    In the above HTML code, we have a div with the id header which we want to fix on the top of the screen and also there is some text to make the page scrollable.

    The jQuery

    <script>
    $(document).ready(function() {
    
        var div = $('#header');
        var start = $(div).offset().top;
    
        $.event.add(window, "scroll", function() {
            var p = $(window).scrollTop();
            $(div).css('position',((p)>start) ? 'fixed' : 'static');
            $(div).css('top',((p)>start) ? '0px' : '');
        });
    
    });
    </script>

    In the javascript code, we added the event listener for a scroll event. The event handler function is called whenever scroll event is fired in the browser window.  
    Then we have added position to header element. We give the div fixed of static position. Also, we have made the top attribute by CSS to 0px if we want to fix it when the page is scrolled down.

     

 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: