Sticky Position with jQuery

Posted by Mihai

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 class="nav">
		<li>Lorem ipsum</li>
		<li>Lorem ipsum</li>
		<li>Lorem ipsum</li>
		<li>Lorem ipsum</li>
		<li>Lorem ipsum</li>
<div class="content">
	<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in mi vehicula arcu blandit euismod eget sed dolor. Suspendisse </p>	

Creating the sticky class that will be added once the navigation is at the top of the page.


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) { 
} else {
$(window).scroll(function() {

You can see the demo bellow.

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.

Leave a Comment

want to read more? here are some Similar posts