Skip to content

Instantly share code, notes, and snippets.

@annelyse
Created May 31, 2022 07:43
Show Gist options
  • Save annelyse/85b56bcfac66896586d765a35b6f7111 to your computer and use it in GitHub Desktop.
Save annelyse/85b56bcfac66896586d765a35b6f7111 to your computer and use it in GitHub Desktop.
//---------------------------//
// ===== Scroll to Top ====
// author: Annelyse Egloff
//---------------------------//
export function returnTop(elementID) {
let el = document.getElementById(elementID);
const scrollToTop = () => {
const speed = 8;
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / speed);
}
};
if (el) {
window.addEventListener("scroll", function () {
const c = document.documentElement.scrollTop || document.body.scrollTop;
// If page is scrolled more than 400
if (c >= (window.outerHeight / 2)) {
el.classList.add('show');
} else {
el.classList.remove('show');
}
})
// on click , go back to top
el.addEventListener('click', event => {
scrollToTop();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment