Skip to content

Instantly share code, notes, and snippets.

@joekolade
Created April 8, 2023 14:11
Show Gist options
  • Select an option

  • Save joekolade/5c7641c927955f7ef6a156493b1e7b5e to your computer and use it in GitHub Desktop.

Select an option

Save joekolade/5c7641c927955f7ef6a156493b1e7b5e to your computer and use it in GitHub Desktop.
[Sticky element JS]
var sticky = function(elementSelector, heightSelector){
var h = document.querySelector(elementSelector);
var stuck = false;
var stickPoint = getDistance(heightSelector);
function getDistance(heightSelector) {
var topDist = h.offsetTop || document.querySelector(heightSelector).offsetHeight;
return topDist;
}
window.onscroll = function(e) {
var distance = getDistance(heightSelector) - window.pageYOffset;
var offset = window.pageYOffset;
if ( (distance <= 0) && !stuck) {
h.classList.add('sticky');
document.body.classList.add('sticky-elements');
stuck = true;
} else if (stuck && (offset <= stickPoint)){
h.classList.remove('sticky');
document.body.classList.remove('sticky-elements');
stuck = false;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment