24 August 2020

Let's create back-to-top button that I have on the bottom of this website. For this let's create a button inside div container with HTML.

<div class="back-to-top" >
      <button class="up-arrow" id="up-button" title="Go to top">
            <img src="up-arrow.png" alt="Back to top button">
      </button>
</div>

Then let's add some styles with CSS.

.back-to-top {
      width: 55px;
      height: 70px;
      background-color: #9ad8d8;
      border-radius: 3px;
}

.up-arrow:hover {
      cursor: pointer;
}

.up-arrow {
      width: 100%;
      height: 100%;
      border: none;
      outline: none;
      padding: 0;
}

Now our back-to-top button looks pretty good. But it still doesn't work.

Now it's time to add some JavaScript code.

let upButton = document.getElementById("up-button");
upButton.onclick = function() {
      document.body.scrollTop = 0; // For Safari
     document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}

In just 3 simple steps you can create back-to-top button. Enjoy!

Photo: Jungwoo Hong