Skip to main content

Back to Top Button

The code snippets below were created by xobot

Here you can learn how to add a "Back to Top" button to your store, for all those pages with 100s of products or just a lot of info.

Demo Page

The Button

To get started we need to add a new button to this store, if you wish to add this to all pages make sure to read or if you wish for it to be only on one page read .

We will add a HTML link into the website, we will customize this to look like a button later in the tutorial.

<a href="#" class="back-to-top" id="backToTopBtn"></a>

When you add this to your page, it will look like nothing is added. This is because we have not customized the button.

Customization

We will use CSS to customize the link, this will allow it to actually look like a button.

<style>
.back-to-top {
position: fixed;
bottom: -40px;
right: 20px;
background-color: #333;
color: #fff;
width: 40px;
height: 40px;
text-align: center;
line-height: 40px;
border-radius: 50%;
transition: bottom 0.3s ease, opacity 0.3s ease;
z-index: 999;
opacity: 0;
cursor: pointer;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.back-to-top.show {
bottom: 20px;
opacity: 1;
}

.back-to-top:hover {
background-color: #555;
}

.back-to-top::before {
content: '\2191';
font-size: 20px;
}
</style>

When you add this to your page, it will look like nothing is added. This is because we have not added a trigger event for the button to appear.

Event Trigger

<script>
function scrollToTop() {
window.scrollTo({
top: 0,
});
}

var backToTopButton = document.getElementById('backToTopBtn');

function toggleBackToTopButton() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
backToTopButton.classList.add('show');
} else {
backToTopButton.classList.remove('show');
}
}

backToTopButton.addEventListener('click', scrollToTop);

window.addEventListener('scroll', toggleBackToTopButton);
</script>

Mobile Optimization

<style>
// Rest of your CSS code

@media screen and (max-width: 600px) {
.back-to-top {
width: 40px;
height: 40px;
line-height: 40px;
}

.back-to-top::before {
font-size: 20px;
}
}
</style>

Smooth Scroll

You may notice that when the button is clicked, it jumps to the top of the page. If you do not like this and would rather have a scroll animation, use the code below.

<style>
html {
scroll-behavior: smooth;
}

// Rest of your CSS code
</style>

Creator Example

Here is an example from "arcaneix" Fourthwall store arcaneix Check out "arcaneix" Fourthwall Shop, made by xobot - Link