Created
January 19, 2023 20:23
-
-
Save mikeoberdick/4d5b9af370afd7c81fb6234c695f6a1d to your computer and use it in GitHub Desktop.
Show scroll to top button as user scrolls down the page
This file contains 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
//HTML | |
<div class = "scrollToTopBtn"><img src="<?php echo get_stylesheet_directory_uri() . '/img/chevron.svg'; ?>" alt="jump to top of page">TOP</div><!-- #jumpScroll --> | |
//JS | |
var scrollToTopBtn = document.querySelector(".scrollToTopBtn") | |
var rootElement = document.documentElement | |
function handleScroll() { | |
// Do something on scroll | |
var scrollTotal = rootElement.scrollHeight - rootElement.clientHeight | |
if ((rootElement.scrollTop / scrollTotal ) > 0.10) { | |
// Show button | |
scrollToTopBtn.classList.add("showBtn") | |
} else { | |
// Hide button | |
scrollToTopBtn.classList.remove("showBtn") | |
} | |
} | |
function scrollToTop() { | |
// Scroll to top logic | |
rootElement.scrollTo({ | |
top: 0, | |
behavior: "smooth" | |
}) | |
} | |
scrollToTopBtn.addEventListener("click", scrollToTop) | |
document.addEventListener("scroll", handleScroll) | |
//CSS | |
.scrollToTopBtn { | |
cursor: pointer; | |
position: fixed; | |
bottom: 30px; | |
right: 30px; | |
background: rgba(256, 256, 256, .5); | |
z-index: 1; | |
height: 50px; | |
width: 50px; | |
opacity: 0; | |
border-radius: 25px; | |
display: flex; | |
justify-content: center; | |
align-items: center; | |
box-shadow: 0 3px 6px rgba(0,0,0,.16); | |
transform: rotate(180deg) translateY(-100px); | |
transition: all .5s ease; | |
img { | |
width: 35px; | |
} | |
&.showBtn { | |
opacity: 1; | |
transform: rotate(180deg) translateY(0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment