Back to Shopify Liquid
Scroll to top button
Shopify Liquid

Scroll to top button

Drop this Shopify Liquid snippet into your theme to add the scroll to top button block. Copy the code below, paste it into your theme files, save and you're done.

52 lines · 1.2 KB
Shopify Liquid
1<div class = "page-width container center-button">
2<button class="btn btn--secondary scroll-top-the-top" onclick="scrollToTop()">Scroll to the top button</button>
3</div>
4
5<style>
6.scroll-top-the-top{
7width: max-content;
8margin: auto;
9margin-top: 10px;
10padding: 10px;
11color: #ffffff;
12border-radius: 8px;
13background: linear-gradient(45deg, #1cbcc3,#1cbcc3, #4abf8f,#4abf8f 80%);
14border: 1px solid #2e2f3c;
15}
16.center-button{
17justify-content: center;
18display: flex;
19}
20</style>
21
22<script>
23function scrollToTop() {
24 const duration = 1000; // Adjust this value to control the scroll speed (in milliseconds)
25 const start = window.pageYOffset;
26 const end = 0;
27 const distance = end - start;
28 const startTime = performance.now();
29
30 function easeInOutQuad(t, b, c, d) {
31 t /= d / 2;
32 if (t < 1) return (c / 2) * t * t + b;
33 t--;
34 return (-c / 2) * (t * (t - 2) - 1) + b;
35 }
36
37 function animateScroll() {
38 const currentTime = performance.now();
39 const timeElapsed = currentTime - startTime;
40
41 window.scroll(0, easeInOutQuad(timeElapsed, start, distance, duration));
42
43 if (timeElapsed < duration) {
44 requestAnimationFrame(animateScroll);
45 } else {
46 window.scroll(0, end);
47 }
48 }
49
50 requestAnimationFrame(animateScroll);
51}
52</script>

Related snippets