Instantly share code, notes, and snippets.
Created
May 23, 2022 06:43
How to create a scroll to top button with JavaScript
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1" /> | |
<title>How to create a scroll to top button with JavaScript</title> | |
<style> | |
html, | |
body { | |
padding: 0; | |
margin: 0; | |
} | |
header { | |
background-color: #073b4c; | |
height: 10vh; | |
} | |
section { | |
height: 90vh; | |
} | |
section.one { | |
background-color: #118ab2; | |
} | |
section.two { | |
background-color: #06d6a0; | |
} | |
section.three { | |
background-color: #ffd166; | |
} | |
#scroll-btn { | |
opacity: 0; | |
width: 40px; | |
height: 40px; | |
color: #fff; | |
background-color: #ef476f; | |
position: fixed; | |
bottom: 10%; | |
right: 10%; | |
border: 2px solid #fff; | |
border-radius: 50%; | |
font: bold 20px monospace; | |
transition: opacity 0.5s, transform 0.5s; | |
} | |
#scroll-btn.show { | |
opacity: 1; | |
transition: opacity 1s, transform 1s; | |
} | |
</style> | |
</head> | |
<body> | |
<header></header> | |
<section class="one"></section> | |
<section class="two"></section> | |
<section class="three"></section> | |
<section class="one"></section> | |
<section class="two"></section> | |
<section class="three"></section> | |
<script> | |
const scrollTop = function () { | |
// create HTML button element | |
const scrollBtn = document.createElement("button"); | |
scrollBtn.innerHTML = "↑"; | |
scrollBtn.setAttribute("id", "scroll-btn"); | |
document.body.appendChild(scrollBtn); | |
// hide/show button based on scroll distance | |
const scrollBtnDisplay = function () { | |
window.scrollY > window.innerHeight | |
? scrollBtn.classList.add("show") | |
: scrollBtn.classList.remove("show"); | |
}; | |
window.addEventListener("scroll", scrollBtnDisplay); | |
// scroll to top when button clicked | |
const scrollWindow = function () { | |
if (window.scrollY != 0) { | |
setTimeout(function () { | |
window.scrollTo(0, window.scrollY - 50); | |
scrollWindow(); | |
}, 10); | |
} | |
}; | |
scrollBtn.addEventListener("click", scrollWindow); | |
}; | |
scrollTop(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source => https://w3collective.com/scroll-to-top-button-javascript/