How to show a button after two scroll events

Viewed 30

I'm trying to make a 'back to top' button that appears after people have scrolled twice on a certain page. I Found the following code online for a button that appears after the user scrolls down 20px but I can't seem to work out how to adapt it so it happens on two scroll events. Please help

<button onclick="topFunction()"id="myBtn" title="Go to top">Top</button>

<script>
    // Get the button
    let mybutton = document.getElementById("myBtn");

    window.onscroll = function() {
      scrollFunction()
    };

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

    function topFunction() {
      document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
    }
</script>
1 Answers

You need to set the style of the myBtn to none by default, and set its position to fixed to be fixed with the screen and not gone with scrolling.

    // Get the button
    let mybutton = document.getElementById("myBtn");

    window.onscroll = function() {
      scrollFunction()
    };

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

    function topFunction() {
      document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
    }
body {
  height: 2000px;
}
#myBtn {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 20px;
  
}
<button onclick="topFunction()"id="myBtn" title="Go to top">Top</button>

Related