CSS, Javascript

How to make a div sticky to the top when you scroll

I’ve seen this one done many different ways, but I wanted the simplest way to do this with just jQuery and some CSS, no extra plugins. Here’s an example in it’s simplest form:

HTML:


everything else on the page here

CSS:

.sticky {
      position: fixed;
      width: 100%;
      left: 0;
      top: 0;
      z-index: 1000;
      border-top: 0;
}

Javascript (requires jQuery to be loaded):

jQuery(window).load(function() {
	var stickyNavTop = jQuery('.navigation').offset().top;  
	  
	function stickyNav() {  
		var scrollTop = jQuery(window).scrollTop();  
			       
		if (scrollTop > stickyNavTop) {   
			    jQuery('.navigation').addClass('sticky');  
		} else {  
		    jQuery('.navigation').removeClass('sticky');   
		}  
	};
	
	jQuery(window).scroll(function() {  
	    stickyNav();  
	}).scroll();
});
Shares