Last active
July 14, 2023 17:44
-
-
Save shaikotahmed19/a9fb914bee41982fed95e240b2dec734 to your computer and use it in GitHub Desktop.
Back to top with 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
<div class="progress-bar" /> | |
<button class="back-to-top hidden"> | |
<svg xmlns="http://www.w3.org/2000/svg" class="back-to-top-icon" fill="none" viewBox="0 0 24 24" stroke="currentColor"> | |
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 11l5-5m0 0l5 5m-5-5v12" /> | |
</svg> | |
</button> | |
<div class="progress-bar" /> |
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
const showOnPx = 100; | |
const backToTopButton = document.querySelector(".back-to-top"); | |
const pageProgressBar = document.querySelector(".progress-bar"); | |
const scrollContainer = () => { | |
return document.documentElement || document.body; | |
}; | |
const goToTop = () => { | |
document.body.scrollIntoView({ | |
behavior: "smooth" | |
}); | |
}; | |
document.addEventListener("scroll", () => { | |
console.log("Scroll Height: ", scrollContainer().scrollHeight); | |
console.log("Client Height: ", scrollContainer().clientHeight); | |
const scrolledPercentage = | |
(scrollContainer().scrollTop / | |
(scrollContainer().scrollHeight - scrollContainer().clientHeight)) * | |
100; | |
pageProgressBar.style.width = `${scrolledPercentage}%`; | |
if (scrollContainer().scrollTop > showOnPx) { | |
backToTopButton.classList.remove("hidden"); | |
} else { | |
backToTopButton.classList.add("hidden"); | |
} | |
}); | |
backToTopButton.addEventListener("click", goToTop); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment