How to add a sticky back-to-top button to your website

How to add a sticky back-to-top button to your website

Morgan Smith's Layout avatar

We’ve all been there. You’ve found a fantastic online guide, scrolled alllllllll the way to the bottom, and then think, “Wow, I’d love to see what else this site has to offer!”

But then you have to scroll.

ALL.

THE.

WAY.

TO.

THE.

TOP.

And then you think…. “Hmmm, nevermind.” And close the page.

As a web designer, this is just about the last thing you want someone to do when they land on a site you’re building. Luckily, the year is 2019 and modern web design best practices have given us the solution to this common UX problem: the sticky back-to-top button.  

What is a sticky back-to-top button?

Also known as a scroll-to-top button or go-to-top image, the sticky back-to-top button is a helpful navigation element that helps users get back to the top of the web page they’re viewing. A common UI pattern is to place this button in the lower right-hand corner of the screen, making it “sticky” via a fixed position so it’s always accessible as the user scrolls down the page.

Things to consider before adding a back-to-top button

Like any popular design trend, I encourage you to take a step back before implementing it on your site to ask yourself: If I’m going to build this, what back-top-button guidelines do I need to follow?

Here are a few questions to answer before you build your scroll-to-top button:

  • Where will it be placed?
  • How big (or small) should it be?
  • What design patterns should you follow so it stays on brand? (Think colors, fonts, icons, etc.)
  • Is it at risk of covering important site content, such as information in a sidebar?
  • What happens on mobile devices? Will it be responsive?
  • Do you actually need it?*

*Note: You could make the argument that users today are conditioned to scroll down (and back up!) on a page, which would eliminate the “need” for a back-to-top button. My advice: Test it! Add a Google Analytics event on click or use a heatmap tool like Hotjar to see how your site visitors engage with the page.

The best “best practice” to follow is one based on data from your own site and users!

How to add a sticky back-to-top button to your WordPress site

In this tutorial, I’ll show you how to add the exact back-to-top button we use here on Layout! The only difference is that we placed ours in a sticky header on the top of the screen, instead of the lower right-hand corner. (But don’t worry, it’s the same concept!)

Pro-tip: While this tutorial isn’t too advanced, I still recommend trying it out on a staging site or local environment, so there’s absolutely no risk to your live site. If you need to set one up quick, check out Local by Flywheel, a free local WordPress app that’s incredibly easy to use.

Let’s get started! I’ll walk through each step of the process, and you can also follow this Codepen from Flywheel’s very own front-end engineer, Josh Masen.


See the Pen ES6 Scroll-to-top button by Josh Lawler (@joshuamasen) on CodePen.

For this sticky back-to-top button tutorial, we’ll use three languages:

  • HTML for the markup to create the button
  • CSS to style the button and have it match your brand
  • JavaScript to make it “work” and define the behaviors of the button

In the HTML, you’ll find the following lines:

<a class="top-link hide" href="" id="js-top">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 6"><path d="M12 6H0l6-6z"/></svg>
  <span class="screen-reader-text">Back to top</span>
</a>

This is going to be your sticky back-to-top button! You can see that we’ve added a CSS class called .top-link, and are using some simple JavaScript to “make it work.” We’re also using an in-line SVG for the button.

Besides an SVG, you could also use an image file or font icon to create the button. We prefer the SVG method, however, because:

  1. It won’t get pixelated at different screen sizes, like a raster image would.
  2. SVGs are universally supported across browsers. (Yay, user experience!)
  3. It’s easy to style with CSS, so you can change everything about it really easily.
  4. It only takes one line of code, making it lightweight and better for site performance.

The last really important piece you’ll find in the HTML is this line:

<span class="screen-reader-text">Back to top</span>

This is critical for users operating with screen readers, and will improve the accessibility of your WordPress site. (Think of it like an alt tag for an image, but for your scroll-to-top button!)

Now let’s talk more about that CSS class, .top-link. We’re using this to actually style up the button, and it’s where you’ll define qualities such as how big it’ll be, how much padding should be around it, the color, etc.

.top-link {
  transition: all .25s ease-in-out;
  position: fixed;
  bottom: 0;
  right: 0;
  display: inline-flex;
  
 cursor: pointer;
 align-items: center;
 justify-content: center;
 margin: 0 3em 3em 0;
 border-radius: 50%;
 padding: .25em;
 width: 80px;
 height: 80px;
 background-color: #F8F8F8;

Note: We’re using Sass (a stylesheet language), to write our CSS a little bit faster. Learn more about this preprocessor here.

A couple important pieces from this snippet: transition: all .25s ease-in-out; controls how “fast” your button will appear or disappear on the screen, and position: fixed; is what makes the button “stick” to the location you want it.

Next, you’ll see rules for .show and .hide. We’ll use JavaScript to switch between these classes in order to tell the browser when the button should (or shouldn’t) appear on the page.

  .show {
    visibility: visible;
    opacity: 1;
  }
  
  .hide {
    visibility: hidden;
    opacity: 0;
  }

Before we go into the JavaScript, there are just a few more lines we’ll add to the CSS.

svg {
 fill: #000;
 width: 24px;
 height: 12px;
}

&amp;:hover {
 background-color: #E8E8E8;

 	svg {
	 fill: #000000;
	}
}

These classes will stylize the SVG image for the arrow itself and tell the browser how to display the button when a user hovers over it.

Finally, we’ll add some CSS to hide the text that says “back to top” for screen readers.

// Text meant only for screen readers.
.screen-reader-text {
	position: absolute;
	clip-path: inset(50%);
	margin: -1px;
	border: 0;
	padding: 0;
	width: 1px;
	height: 1px;
	overflow: hidden;
	word-wrap: normal !important;
	clip: rect(1px, 1px, 1px, 1px);

	&amp;:focus {
		display: block;
		top: 5px;
		left: 5px;
		z-index: 100000; // Above WP toolbar
		clip-path: none;
		background-color: #eee;
		padding: 15px 23px 14px;
		width: auto;
		height: auto;
		text-decoration: none;
		line-height: normal;
		color: #444;
		font-size: 1em;
		clip: auto !important;
	}
}

Now on to the JavaScript! We’re going to do this without loading jQuery, which will help keep your code lightweight and quick to load.

The first variable will help the browser find the button.

// Set a variable for our button element.
const scrollToTopButton = document.getElementById('js-top');

Next, we’ll create a function that shows the scroll-to-top button if the user scrolls beyond the height of the initial window.

const scrollFunc = () => {
  // Get the current scroll value
  let y = window.scrollY;
  
  // If the scroll value is greater than the window height, let's add a class to the scroll-to-top button to show it!
  if (y > 0) {
    scrollToTopButton.className = "top-link show";
  } else {
    scrollToTopButton.className = "top-link hide";
  }
};

We’ll also add an event listener, which will watch as the user scrolls (so we know where they’re at on the page).

window.addEventListener("scroll", scrollFunc);

Almost done! Next, we need to define the function that makes the button actually take the user back to the top of the page. To do that, we’ll create a variable for the number of pixels we are from the top of the page. If that number is greater than 0, the function will set it back to 0, taking us to the top!

We’ll also add a little animation here, so the jump isn’t too sudden.

const scrollToTop = () => {
  // Let's set a variable for the number of pixels we are from the top of the document.
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  
  // If that number is greater than 0, we'll scroll back to 0, or the top of the document.
  // We'll also animate that scroll with requestAnimationFrame:
  // https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    // ScrollTo takes an x and a y coordinate.
    // Increase the '10' value to get a smoother/slower scroll!
    window.scrollTo(0, c - c / 10);
  }
};

Last but not least, we just need to tell the page to run that function when someone clicks our sticky back-to-top button.

// When the button is clicked, run our ScrolltoTop function above!
scrollToTopButton.onclick = function(e) {
  e.preventDefault();
  scrollToTop();
}

Next: Discover the 19 WordPress plugins developers love

Download this ebook for a list of our most recommended plugins for developers! We’ve found all of these plugins to be straightforward to use, not too performance heavy on your site, and just downright reliable.


That’s it! You’ll now have a fully functioning and customizable sticky back-to-top button on your WordPress site. To see the entire tutorial in action, remember to check out this Codepen from Flywheel’s very own front-end engineer, Josh Masen!

Comments ( 1 )

  1. bb

    July 13, 2019

    thank you so much! this is the only back-to-top button tutorial I've found that was super easy to get working on my own site! thanks again!!!!

Join the discussion