Adding a Back to Top Feature to the Website

The Hugo Clarity skin used on this site comes with a built-in back-to-top feature. I wasn't satisfied with the icon, so I changed it to its current form for easier identification. The "Back to Home" icon is always visible, which is a bit annoying. So, we need to optimize it so that it's not displayed by default. Only when the scrollbar scrolls down a certain distance, exceeding this threshold, will the "Back to Top" icon appear. Beyond that, it will be hidden.

The implementation logic is simple and easy to understand. The entire change is shown in the image below:

hugo back to top

The changes are explained below.

1. Add an id to the element containing the icon

Adding an id is to facilitate subsequent operations and control whether the icon is displayed. The changes are as follows:

 1diff --git a/layouts/partials/top.html b/layouts/partials/top.html
 2index bdaa538..33aade0 100644
 3--- a/layouts/partials/top.html
 4+++ b/layouts/partials/top.html
 5@@ -1,3 +1,3 @@
 6-<a class="to_top" id="toTop" href="#documentTop">
 7- <img src="/icons/to-top.svg" width="44" height="44" alt="to-top" />
 8-</a>
 9+<a class="to_top" href="#documentTop">
10+ <img src="/icons/to-top.svg" width="44" height="44" alt="to-top">
11+</a>
12\No newline at end of file

The difference is that the tag has an id="toTop" added to it.

2. Setting the default hidden icon

The visibility: to_top property has been added. hidden means hidden by default. The element is still there. This improves performance (it doesn't need to be frequently created/deleted during scrolling), but it still affects the layout.

3. Add control logic

The custom JS code for this skin is placed in custom.js and is originally empty. The code above executes the function inside during scrolling. If the vertical offset from the top (how much is hidden due to scrolling) is greater than 1000 pixels, the element with the id toTop is made visible; otherwise, it is hidden. The effect is that the icon appears when scrolling down a certain distance, and disappears when scrolling down a certain distance.

Explanation of scrollTop in English:

An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, its scrollTop value is 0.

If you still don't understand, see this stackoverflow answer.

scrollTop cat

Finally, since the page anchor "documentTop" is above the body element, clicking it will return to the top. Readers can scroll through the site to see how this works. Of course, every website's code structure is different. Once you understand the principles, you can add this functionality yourself. I'm not a front-end professional, so this implementation isn't necessarily the best practice, but it works for me, and I'm sharing it for non-professionals to use as a reference.

Lastmod: Friday, January 16, 2026

See Also:

Translations: