JQuery

JQuery sticky header example

JQuery sticky header example, someone asked me to explain?

In this article I will show you sticky header on scroll jQuery using css. This effect will take place when the user scroll down the page and it reaches height 72px with the help of window.scroll function. The sticky class is getting activated and subheading will stick on the top of the page.

Copy and paste the Html code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title></title>
    <style type="text/css">
        body {
            height: 2000px;
        }
 
        header {
            height: 72px;
            border-bottom: 1px solid #000;
            padding: 10px 0;
        }
 
        #sub_head {
            height: 18px;
            border-bottom: 1px solid #ccc;
            padding: 5px 0;
        }
 
            #sub_head.sticky {
               position: fixed;
                top: 0px;
                left: 0px;
                right: 0px;
                z-index: 99999;
            }
    </style>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $(window).scroll(function () {
                if ($(window).scrollTop() > 72) {
                    $("#sub_head").addClass("sticky");
                } else {
                    $("#sub_head").removeClass("sticky");
                }
            });
        });
 
    </script>
</head>
<body>
    <header>
        <img src="http://www.infinetsoft.com/Uploads/20160523103730logosmall.png" />
    </header>
    <div id="sub_head">
        some sub header 
    </div>
</body>
</html> 

Description: The html page contains header tag(has logo), div tag (id as sub_head) and sticky fixed header css class. When the user scrolls down the page window, scroll jQuery function calls and sticky class(fixed header css) will get added using jQuery addclass property i.e (fixed header on scroll jQuery) . If the user scrolls up, the css class sticky will get removed and the page will display as normal.

jquery sticky header

Post your comments / questions