Sometimes plugins, site-builders, or other circumstances make it difficult or impossible to make a sticky-scrolling element. That’s where Waypoint JS comes in. Using this, the following script will appropriately add or remove the “sticky” class. Then, you can use CSS to fix the element’s position.
Here’s a snippet I have made use of:
jQuery(document).ready(function () {
// Choose the element to be "sticky"
var stickyElement = jQuery('#element-id');
// This will be used to disable sticky when scrolling back up
var stickyElementPosition = '';
// This will remove the "sticky" class if the user scrolls up higher than the element's original position
var intervalId = window.setInterval(function () {
if (window.scrollY < stickyElementPosition) {
// Only remove if it already has the class
if (stickyElement.hasClass('sticky')) {
stickyElement.removeClass('sticky');
stickyElementPosition = "";
}
}
}, 100);
var waypoint = new Waypoint({
element: stickyElement,
handler: function (direction) {
if (stickyElementPosition == "") {
// Remember the element's original position
stickyElementPosition = window.scrollY;
}
// Only add the class if it isn't there
if (!stickyElement.hasClass('sticky')) {
stickyElement.addClass('sticky');
}
},
offset: 20
})
});
And the CSS:
.sticky {
position: fixed;
top: 20px;
}