skip to Main Content

I know how to make a back to top button, but how do I only make it appear once I scroll down slightly. Does anyone know how to make this happen? ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍
‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍

3

Answers


  1. Here is one solution you can try.

    window.onscroll = function() {scrollFunction()};
    
    function scrollFunction() {
      const backToTopBtn = document.getElementById("backToTopBtn");
      if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
        backToTopBtn.classList.add("show");
      } else {
        backToTopBtn.classList.remove("show");
      }
    }
    
    function scrollToTop() {
      document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
    }
    #backToTopBtn {
      display: none;
      position: fixed;
      bottom: 20px;
      right: 20px;
      opacity: 0;
      transition: opacity 0.3s ease-in-out;
    }
    
    #backToTopBtn.show {
      display: block;
      opacity: 1;
    }
    <button id="backToTopBtn" onclick="scrollToTop()">Back to Top</button>
    Login or Signup to reply.
  2. try this one

    let go_to_top = document.querySelector(".go-top");
    
    // functions occure win scrolliong 
    window.onscroll= function(){
          if(scrollY<=520){
            go_to_top.style.display="none";
          }
          else {
            go_to_top.style.display="flex";
          }
    }
    //go to top 
    function go_top(){
      window.scrollTo(0,0);
    }
      <div class="go-top" onclick="go_top()">
          <i class="fa-solid fa-arrow-up"></i>
       </div>
    Login or Signup to reply.
  3. CSS:

    #scrollTop {
        display: none;
        position: fixed;
        cursor: pointer;
        transition: 1s;
        text-decoration: none;
        background-color: green;
    }
    
    #scrollTop:hover {
        transition: 1s;
        background-color: lightgreen;
    }
    
    #scrollTop:active {
        background-color: greenyellow;
    }
    

    JS:

    var scrollTop = document.getElementById("scrollTop");
    
    window.onscroll = function(){
        scrollfunction()
    };
    function scrollfunction(){
        if( document.body.scrollTop > 20 || document.documentElement.scrollTop > 20){
            scrollTop.style.display = "block";
        } else {
            scrollTop.style.display = "none";
        }
    }
    
    scrollTop.addEventListener("click", function(){
        window.scrollTo({
            left: 0,
            top: 0,
            behavior: "smooth"
        })
    })
    

    HTML:

    <body>
      <div class="content">
          your content here
      </div>
    </body>
    
    <button id="scrollTop">
       <i class=""></i>
    </button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search