Scroll Back To Top Button Code Snippet

Resources

  • https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css
  • https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css
  • https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js

Useful links

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <link crossorigin='anonymous' href='https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css' integrity='sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC' rel='stylesheet'/>
    <link href='https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css' rel='stylesheet' type='text/css'/>
    <style>
      body {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 20px;
      }
      #hdo-scroll-top-button {
      display: none;
      position: fixed;
      bottom: 20px;
      right: 30px;
      z-index: 99;
      font-size: 18px;
      border: none;
      outline: none;
      background-color: #1877F2;
      color: white;
      cursor: pointer;
      border-radius: 10px;
      opacity: 0.7;
      }
      #hdo-scroll-top-button:hover {
      background-color: #1877F2;
      opacity: 1;
      }
      #hdo-scroll-top-button i {
      margin-top: 5px;
      font-size: 32px;
      }
    </style>
  </head>
  <body>
    
Scroll Down
This is about how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.
<script src='https://code.jquery.com/jquery-3.5.0.js' type='text/javascript'></script> <script> $(document).ready(function(){ //add scroll top button $("body").append(''); // Get the button let mybutton = document.getElementById("hdo-scroll-top-button"); // When the user scrolls down 20px from the top of the document, show the button window.onscroll = function() {scrollFunction()}; function scrollFunction() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { mybutton.style.display = "block"; } else { mybutton.style.display = "none"; } } // When the user clicks on the button, scroll to the top of the document $("#hdo-scroll-top-button").click(function(){ $("html, body").animate({ scrollTop: "0" }); }); }); </script> </body> </html>

Code Repo