Scroll To Top With JavaScript

In this tutorial, We’ll learn about how to scroll to the top using js.

We’ll understand it by one example,

First we add four section in a html document and add button for a ScrollToTop and we use top icon button.

<i class=”fa fa-arrow-up” aria-hidden=”true”></i>


<button class="backtotop" id="backtotop" onclick="topFunction()"><i class="fa fa-arrow-up" aria-hidden="true"></i></button>
<section class="top-classs">
    <h1>first page home</h1>
<section class="second-classs">
    <h1>second page home</h1>
<section class="third-classs">
    <h1>third page home</h1>
<section class="four-classs">
    <h1>forth page home</h1>

style.css :

Here is some style for section and button

html { scroll-behavior: smooth; }

the above css use  to scroll page smoothly.

      * {
          margin: 0;
          padding: 0;
      html {
          scroll-behavior: smooth;
      .four-classs {
          background-color: silver;
          height: 100vh;
      .second-classs {
          background-color: gray;
      .third-classs {
          background-color: darkgray;
      .four-classs {
          background-color: black;
      .backtotop {
          background-color: white;
          height: 50px;
          width: 50px;
          padding: 20px;
          border-radius: 50%;
          border: 1px solid red;
          z-index: 999;
          position: fixed;
          bottom: 30px;
          right: 30px;
          display: none;
      .backtotop i {
          color: black;
          font-size: 20px;
          position: relative;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
      h1 {
          color: white;
          text-align: center;
          padding-top: 150px;
          text-transform: capitalize;

custom.js :

Now in the JavaScript file :

first, we select a link button.

var backtotop= document.getElementById(“backtotop”)

then define a function to scroll page to top,

When the we scroll the page after scroll Top 350 then the button will display .If page is below 350 then scroll button not display

if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350)

Now when we click on this button it scroll to top and button will be not display.

    var backtTotop = document.getElementById("backtotop")

    window.onscroll = function() {

    function scrollFunction() {
        if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) {
   = "block";
        } else {
   = "none";

    function topFunction() {
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories