How to add a back to top button

Dan Counsell · Founder of Realmac SoftwareUpdated

We’ve made RapidWeaver, a website builder for Mac, since 2004. Each guide works with any tool, then shows how in RapidWeaver Elements.

On a long page, a back to top button saves a lot of scrolling, especially on phones. Here’s how to add one that works well.

The simplest back to top button

Put an ID at the top of your page, and a link that points to it:

<body id="top">
  ...
  <a href="#top" class="back-to-top">Back to top</a>
</body>

Then fix it to the bottom right corner:

.back-to-top {
  position: fixed;
  right: 1.5rem;
  bottom: 1.5rem;
  padding: 0.75rem 1rem;
  border-radius: 9999px;
  background: #111;
  color: #fff;
}
html { scroll-behavior: smooth; }

That’s all you need. No JavaScript, and it works even if scripts fail.

Show it only after scrolling

A button that’s visible at the top of the page is pointless. This script hides it until the visitor has scrolled a screen’s height:

<script>
  const button = document.querySelector('.back-to-top');
  const toggle = () => button.hidden = window.scrollY < window.innerHeight;
  window.addEventListener('scroll', toggle, { passive: true });
  toggle();
</script>

Respect reduced motion

Some people turn off animations because motion makes them unwell. Turn off smooth scrolling for them:

@media (prefers-reduced-motion: reduce) {
  html { scroll-behavior: auto; }
}

Make it accessible

  • Use a real link or button, not a div.
  • If the button is just an arrow icon, give it a label: aria-label="Back to top".
  • Make it at least 44 pixels square so it’s easy to tap.
  • Keep it out of the way of other buttons, such as a chat widget.

Add a back to top button in RapidWeaver Elements

RapidWeaver Elements doesn’t need a special component for this. A Button and an anchor do the job:

  1. Select the first component on the page and give it an ID under Advanced > ID, such as top.
  2. Add a Button, open Link > To, choose Anchor and pick that ID.
  3. Fix the button to a corner with Tailwind classes such as fixed bottom-6 right-6.

Anchor links scroll smoothly in Elements by default.

Questions about back to top buttons

Where should a back to top button go?

The bottom right corner is what people expect. On phones, make sure it doesn’t cover content or other buttons.

Do I need JavaScript for a back to top button?

No. A link to #top and the CSS above work without it. JavaScript only adds the show-after-scrolling part.

Get RapidWeaver Elements for Mac

Design, build and publish your site without code, then host it anywhere. Try it free on your own project.

Download

Confirm your email and we'll send your code. Unsubscribe any time. Privacy policy