c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
JQuery

JQuery sticky header example

| | Html , JQuery

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.