Skip to content

Instantly share code, notes, and snippets.

@hsnyc
Last active March 30, 2019 16:59
Show Gist options
  • Save hsnyc/3ec7cae7ae5ce7c50570c088cb91d4e3 to your computer and use it in GitHub Desktop.
Save hsnyc/3ec7cae7ae5ce7c50570c088cb91d4e3 to your computer and use it in GitHub Desktop.
When the user scrolls down 1020px from the top of the document, show a button that will scroll back to the top of the page
/* Back to Top Icon */
#btt-icon {
width: 46px;
height: 50px;
position: fixed;
bottom: 40px;
right: 40px;
background-color: rgba(136, 136, 136, 0.18);
cursor: pointer;
border-radius: .2rem;
display: none;
align-items: center;
justify-content: center;
}
#btt-arrow {
position: relative;
width: 0;
height: 0;
border-style: solid;
border-width: 0 15px 20px 15px;
border-color: transparent transparent #0075C9 transparent;
z-index: 99;
}
@keyframes bounceUp {
0% {
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-o-transform: translateY(0px);
-ms-transform: translateY(0px);
transform: translateY(0px); }
100% {
-webkit-transform: translateY(-12px);
-moz-transform: translateY(-12px);
-o-transform: translateY(-12px);
-ms-transform: translateY(-12px);
transform: translateY(-12px); } }
/* Back to Top Icon Ends */
<!-- Back to Top Icon -->
<div id="btt-icon">
<div id="btt-arrow"></div>
</div>
// Scroll to Top ============================================= //
// When the user scrolls down 1020px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
var bttIcon = document.getElementById("btt-icon");
var bttArrow = document.getElementById("btt-arrow");
function scrollFunction() {
if (document.body.scrollTop > 1820 || document.documentElement.scrollTop > 1820) {
bttIcon.style.display = "flex";
} else {
bttIcon.style.display = "none";
}
}
bttIcon.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector('header').scrollIntoView({
behavior: 'smooth'
});
});
bttIcon.addEventListener("mouseover", bounceArrow, false);
function bounceArrow() {
bttArrow.style.animation = "bounceUp .4s ease-in-out infinite";
}
bttIcon.addEventListener("mouseout", bounceStop, false);
function bounceStop() {
bttArrow.removeAttribute("style");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment