Now a days the site contains some long page content so we need to put back to top button in our design. It will be very user friendly User Interface. In this blog we will learn how to create a scroll to top button with JavaScript.

HTML

Put the following code in HTML part

<button onclick="CodeCanalTopFun()" id="CCBtn" title="Go to top">Top</button>

CSS

#CCBtn{
  background-color: #d7d7d7;
  border: medium none;
  border-radius: 8px;
  bottom: 20px;
  color: white;
  cursor: pointer;
  display: none;
  outline: medium none;
  padding: 10px 15px 7px;
  position: fixed;
  right: 30px;
  z-index: 99;
  font-size: 20px;
  opacity : 0.5;
}

#CCBtn:hover {
 opacity:1; /* Make button visible on hover */
}

JavaScript

// When the user scrolls down 20px from the top of the document,we will show the button
window.onscroll = function() {CodeCanalScrollFun()};

function CodeCanalScrollFun() {
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
        document.getElementById("CCBtn").style.display = "block";
    } else {
        document.getElementById("CCBtn").style.display = "none";
    }
}

// When the user clicks on the back to top button,it'll scroll to the top of the document smoothly
function CodeCanalTopFun() {
    $('html, body').animate({scrollTop: 0}, 1000);
    return false;
} 

Now your back to button is ready to use. You can change the design of the button as per your requirement.

There are currently no comments.