The Sticky Position is used to make an element “stick” to the top of the page once a user has scrolled past it. For example, Facebook sticks to the top of the page as a blue bar.
In this post, I will show you how to create a simple nav that will stick to the top of the page even after you’ve scrolled past it.
<div class="header">
This is the header
</div>
<div class="nav">
<ul>
<li>Lorem ipsum</li>
<li>Lorem ipsum</li>
<li>Lorem ipsum</li>
<li>Lorem ipsum</li>
<li>Lorem ipsum</li>
</ul>
</div>
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing.</p>
</div>
Creating the sticky class that will be added once the navigation is at the top of the page.
.sticky{
position:fixed;
top:0;
left:0;
right:0;
z-index:9999;
}
The class will be applied with jQuery if the navigation touches the top of the page.
$(document).ready(function() {
var stickyNavTop = $('.nav').offset().top;
var stickyNav = function(){
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyNavTop) {
$('.nav').addClass('sticky');
} else {
$('.nav').removeClass('sticky');
}
};
stickyNav();
$(window).scroll(function() {
stickyNav();
});
});
You can see the demo bellow.
See the Pen Sticky Position with jQuery by Mihai Slujitoru (@MihaiSlujitoru) on CodePen.
See the Pen Sticky Position with jQuery by Mihai Slujitoru (@MihaiSlujitoru) on CodePen.
If you are trying to add other effects to your page, such as showing an image only once the user reaches it, I like to use Waypoints library.