skip to content

Smooth scroll-to-top

Back in the day, circa 2010, when we needed to scroll to top we would use the jQuery library to accomplish this.

I dug out the following snippet from a project I launched way back in 2010. While the project is long since obsolete, it does serve to show just how far we've come:

// Select all links with hashes
 .click(function (event) {
  if (
   location.pathname.replace(/^\//, "") ==
    this.pathname.replace(/^\//, "") &&
   location.hostname == this.hostname
  ) {
   var target = $(this.hash);
   target = target.length ? target : $("[name=" + this.hash.slice(1) + "]");
   if (target.length) {
    $("html, body").animate(
      scrollTop: target.offset().top,
     function () {
      var $target = $(target);
      if ($":focus")) {
       return false;
      } else {
       $target.attr("tabindex", "-1");

I believe this, or at least a version of it, was originally posted by Chris Coyier over at, though I can't be sure.

It simply targets all # links and applies smooth scrolling to their respective elements.

Today there's luckily a much simpler and better way to achieve this effect, and it's even available in native Javascript:

<button onclick="scrollToTop();">scroll-to-top</button>

 function scrollToTop() {
   top: 0,
   left: 0,
   behavior: "smooth",

Simply trigger this function with a button at the position you want to scroll from and watch the window magically scroll to the top.

I've recently implemented this feature in the footer on this site.

Try it for yourself: ↑ Top ↑