There are several tutorials on how to make things “sticky” using CSS. We will make a “sometimes sticky” element using CSS and jQuery. Here is an article on CSS sticky footers to help you understand before we move onto the “sometimes” part using jQuery.
Remember – position: fixed;
in a CSS sticky element is in a fixed position relative to the element or “container” it’s in.
CSS Sticky Class
The main points for this CSS sticky element are position: fixed;
and top: 75px;
Z-index helps keep it “on top” when the user scrolls.
.sticky {
position: fixed;
top: 75px;
}
HTML for Sometimes Sticky Element
This is just a general idea of the HTML needed.
<body>
<div id="wrapper">
<div id="leftSideBar">
<p>lots of content</p>
<div id="stickyChunk">
<p>stuff</p>
</div>
<p>lots of content</p>
</div>
<div id="mainContent">
<p>lots of content</p>
</div>
</div>
</body>
jQuery for Sometimes Sticky Element
$(document).ready(function() {
var stickyNavTop = $('#stickyChunk').offset().top;
var stickyNav = function(){
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyNavTop)
{
$('#stickyChunk').addClass('sticky');
}
else
{
$('#stickyChunk').removeClass('sticky');
}
};
stickyNav();
$(window).scroll(function() {
stickyNav();
});
});