Saturday, 5 April 2014

How to create fixed header when scrolling the page using JQuery?

Description:

Welcome to Jqueryjohn.com.

In this article, I will explain how to create fixed header while scrolling the page using Jquery.  

While doing scrolling on the webpage, the header should remain top of the screen. To implement this functionality, I have used simple JavaScript code.

Create a header div which we want to freeze at the top.

In the below code, I have added event listener to scroll event. This event is called each time when scroll event is fired.

While page is scrolling down, set the top attribute to 0px and make the header position fixed.

For live demo, click here.


Example program:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-1.9.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var fixHeader = $('#fixedHeader').offset().top;
            $(window).scroll(function () {
                if ($(window).scrollTop() > fixHeader) {
                    $('#fixedHeader').css({ position: 'fixed', top: '0px' });
                } else {
                    $('#fixedHeader').css({ position: 'static', top: '0px' });
                }
            });
        });
    </script>
    <style type="text/css">
        #fixedHeader
        {
            background-color: Gray;
            height: 60px;
            width: 990px;
        }
        #fixedHeader ul
        {
            margin: 0 10px;
            padding: 10px 40px 15px;
            box-shadow: 0 12px 5px -6px rgba(0, 0, 0, 0.5);
        }
        #fixedHeader ul li
        {
            display: inline;
            font-weight: bold;
            margin: 0 20px;
        }
    </style>
</head>
<body>
    <div id="fixedHeader">
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Articles</a></li>
            <li><a href="#">Tutorials</a></li>
            <li><a href="#">PlugIns</a></li>
        </ul>
    </div>
    <div id="content">
        <h3>
            Add your page content Here</h3>
        <p>
            This is the sample content for the page.
        </p>
    </div>
</body>
</html>


Create fixed header while scrolling using jquery, fixed header using jquery, facebook like header with fixed position, jquery scrollable div with fixed header

No comments:

Post a Comment