Skip to content

Instantly share code, notes, and snippets.

@agusputra
Last active November 3, 2019 15:47
Show Gist options
  • Save agusputra/5c9010bfb4adac23faff40c3e89800dd to your computer and use it in GitHub Desktop.
Save agusputra/5c9010bfb4adac23faff40c3e89800dd to your computer and use it in GitHub Desktop.
Make element sticky to the viewport when scroll
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