HTML logoCSS Frontend Programming HTML Javascript jQuery 

How to stick header to top using HTML/CSS/Javascript

To stick header / Fix the Header to top Follow these Steps

1.Create a Div in Html as shown in the below code

<section>
  <div class="sticky">
<ul>
<li>home</li>
<li>about</li>
</ul>
</div>
</section>
HTML Code

2. then add CSS, to it Position:fixed is very important to fix the header.

body { margin: 0; }
ul{
overflow-x:hidden;
white-space:nowrap;
height: 1em;
width: 100%;
}

li{
display:inline;
margin-left:10px;
}
section {
height: 2000px;
padding-top: 100px; }

.sticky { background: orange; }

.fixed {
position: fixed;
top:0; left:0;
width: 100%; }
CSS Code

3. Then add JS

$(window).scroll(function(){
var sticky = $('.sticky'),
scroll = $(window).scrollTop();

if (scroll >= 100) sticky.addClass('fixed');
else sticky.removeClass('fixed');
});
javascript

you can also use this too. If the trigger point is unknown but should be whenever the sticky element reaches the top of the screen, offset().top can be used. then you can use the JS.

var stickyOffset = $('.sticky').offset().top;

$(window).scroll(function(){
var sticky = $('.sticky'),
scroll = $(window).scrollTop();

if (scroll >= stickyOffset) sticky.addClass('fixed');
else sticky.removeClass('fixed');
});
Javascript

.
DEMO :http://jsfiddle.net/gxRC9/502/

Also Read:  How to integrate Razorpay checkout using javascript

Related posts