Last active
November 3, 2019 15:47
-
-
Save agusputra/5c9010bfb4adac23faff40c3e89800dd to your computer and use it in GitHub Desktop.
Make element sticky to the viewport when scroll
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
function setSticky(elementId) { | |
const stickyElement = document.getElementById(elementId) | |
const stickyTop = stickyElement.offsetTop | |
const setStickyClass = () => { | |
if (window.pageYOffset > stickyTop) { | |
stickyElement.classList.add('sticky') | |
} | |
else { | |
stickyElement.classList.remove('sticky') | |
} | |
} | |
window.onscroll = setStickyClass | |
return setStickyClass | |
} | |
// setSticky('elementIdSelector') | |
/* | |
// CSS | |
.sticky { | |
position: fixed; | |
top: 0; | |
max-height: 100vh; | |
overflow-y: scroll; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment