Hugo + js = back to top button

Hugo + js = back to top button

Example on how to add a back to top button. This has nothing to do with Hugo itself, it is just a minimal Javascript snipped that allows you to jump back to the top of the page.

This article is a fork of the back-to-top feature from Hugo meme theme, all credit goes to reuixiy.

This article was written for Hugo 0.70.

Code

The code is completely optional, it will work with just HTML as well. The Javascript will automatically show/hide the back to top button depending on how far the page is scrolled down. In addition a throttle function is added on scroll so the page goes smoothly to the top instead of instantly “teleporting”. If you have many scroll eventhandlers you might want to leave out the throttle function for better performance.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Credits: https://www.30secondsofcode.org/js/s/throttle/
const throttle = (fn, wait) => {
    let inThrottle, lastFn, lastTime;
    return function () {
        const context = this,
            args = arguments;
        if (!inThrottle) {
            fn.apply(context, args);
            lastTime = Date.now();
            inThrottle = true;
        } else {
            clearTimeout(lastFn);
            lastFn = setTimeout(function () {
                if (Date.now() - lastTime >= wait) {
                    fn.apply(context, args);
                    lastTime = Date.now();
                }
            }, Math.max(wait - (Date.now() - lastTime), 0));
        }
    };
};

// ================================================

const backToTop = document.getElementById("back-to-top");
window.addEventListener("scroll",
    throttle(function () {
        window.scrollY > 100 ? backToTop.classList.add("show") : backToTop.classList.remove("show");
    }, 1000)
);  

In HTML add a back to top button, anywhere usually at the bottom of the viewport.

<div id="back-to-top">
    <a href="#">{{ partial "inline-svg" .Site.Params.content.backToTopIcon }}</a>
</div>

Finally the SCSS.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#back-to-top {
  visibility: hidden;
  bottom: 0;
  position: fixed;
  right: 0;
  z-index: 1;

  &.show {
    visibility: visible;
  }

  a {
    display: block;
    padding: 1em;
    padding-right: 0.5em;
    color: var(--font-color);

    &:hover {
      color: var(--primary-color);
    }
  }
}
Noticed an error in this post? Corrections are appreciated.

© Nelis Oostens