This post shows how to create a back-to-top button that redirects to the top of the page. I used only HTML, CSS & JavaScript. You can also download the template from my GitHub account. Please see the demo of the finished product.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<a id="gotop" class="backtotop" href="javascript:void(0)"
><img src="./img/top-arrow.svg" alt="back to top button"
/></a>
<script src="script.js"></script>
</body>
</html>
You can download the top-arrow.svg from this link. I have this icon in an “img” folder. If your project setup is different than mine, don’t forget to update the file/image path in the HTML.
Let’s see the CSS below.
CSS
.backtotop {
opacity: 0;
visibility: hidden;
width: 40px;
height: 40px;
background-color: #e1433c;
position: fixed;
bottom: 20px;
right: 10px;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
justify-content: center;
align-items: center;
transition: 0.3s ease-in;
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
}
.backtotop img {
width: 50%;
height: auto;
}
.backtotop.active {
opacity: 1;
visibility: visible;
}
.backtotop:hover {
background-color: #fe701b;
}
The active
class is added to the anchor tag by JavaScript. It also removes the class if the scroll position is less than 30%. You’ll see it in the JavaScript.
JavaScript
const gototop = document.getElementById("gotop")
const onScroll = () => {
const scroll = document.documentElement.scrollTop
const threshold = window.innerHeight * 0.3
if (scroll > threshold) {
gototop.classList.add("active")
} else {
gototop.classList.remove("active")
}
};
window.addEventListener("scroll", onScroll)
gototop.addEventListener("click", () => {
window.scrollTo({
top: 0,
behavior: "smooth",
})
})
document.documentElement.scrollTop
gives you the scroll amount in pixels. window.innerHeight * 0.3
measures if the scroll position is 30%.
In the condition, if the scroll position is greater than 30%, we are adding the active
class to the anchor tag. It also removes the class if the condition is not true (less than 30%).
Finally, we have a click even that redirects to the very top of the window if someone clicks the button or anchor tag.
Build HTML CSS projects
I tried to make this post as easy as possible. If you have any difficulties following this guideline, let me know so I can make further improvements.
You can also download the entire project from my GitHub repository.