How to make scroll to top button in html with smooth scrolling

In this tutorial you are going to learn how to make a scroll to top button in HTML

Lets Begin

We are going to use jQuery in this tutorial for some smooth animations, for that we need to include it in the <head> section of the html file. Also we are going to use separate files for css and javascript so the <head> section will look somewhat like this:
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>

Step 1: The HTML code

Just put this tag inside the <body> of the html code after the contents of the page:
<a id="scroll-top" style="display: none;"><span></span></a>
This creates the scroll to top button and next we are going to make an upward arrow symbol in it.

Step 2: The CSS code

In this step we are going to create an upward arrow inside the button by using css but you cannot see it because of the inline css style="display: none;" but it does not matter for now because we are going to deal it with javascript, here is the css code:
#scroll-top {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 50px;
  height: 50px;
  font-size: 32px;
  background: #ff9d00;
  border-radius: 100%;
  cursor: pointer;
}
#scroll-top span {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -8px;
  margin-top: -12px;
  height: 0;
  width: 0;
  border: 8px solid transparent;
  border-bottom-color: #ffffff;
}
#scroll-top:hover {
  transition: 0.3s;
  box-shadow: 0 0 20px 4px #fff;
}

Step 3: The Javascript code

This is the javascript code:
$(document).ready(function() {
  $(window).scroll(function() {
    if ($(this).scrollTop() > 100) {
      $("#scroll-top").fadeIn();
    } else {
      $("#scroll-top").fadeOut();
    }
  });
  $("#scroll-top").click(function() {
    $("html, body").animate({ scrollTop: 0 }, 500);
    return false;
  });
});

Demo

Done

Thank you for reading till the end. Ask questions in the comments section. I will reply as soon as possible. Share this post if you found it helpful.

Comments