Mar 22, 2018 - James Mejia

Creating a Sticky Back-to-Top Button

See the Pen Stick to Footer by James Mejia (@mejiaj) on CodePen.

Recently, one of our designers had an idea for a sticky back-to-op button. I really liked the idea from a UX perspective, because it was a great utility button to have and it didn't get in the way of browsing. If you open the pen, you'll see that the button is fixed to the bottom window as you scroll. When you reach the footer it becomes stuck to the top of it.

There are quite a few ways to tackle this—and many more ways to improve it—so feel free to fork the pen and build on it.

We'll start off with the JS, which is incredibly simple. We're checking for two things: if the user is scrolling, and if you can actually see the footer.

var stickyFooter = debounce(function(){ $footer.isInViewport() ? $backToTop.addClass('is-stuck').removeClass('is-sticky') : $backToTop.addClass('is-sticky').removeClass('is-stuck'); }, 100);

Here we're checking if the footer is in view. If it is, then we're adding the stuck class; otherwise we're replacing that with is-sticky. The debounce function is there so the function isn't called on with every scroll. That would create a laggy experience.
Once we add the is-stuck class, we add a little CSS animation that makes it pop up. You can take it further by making it pop up and down based on the direction of the scroll. It  was just a great little exercise.