Skip to content

Instantly share code, notes, and snippets.

@w3collective
Created May 23, 2022 06:43
Show Gist options
  • Save w3collective/fe95e0d45b8cacfa2327470db8e320b4 to your computer and use it in GitHub Desktop.
Save w3collective/fe95e0d45b8cacfa2327470db8e320b4 to your computer and use it in GitHub Desktop.
How to create a scroll to top button with JavaScript
<!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 = "&uarr;";
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>
@w3collective
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment