Created
April 8, 2023 14:11
-
-
Save joekolade/5c7641c927955f7ef6a156493b1e7b5e to your computer and use it in GitHub Desktop.
[Sticky element JS]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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