0

Here is a simple html page with my sticky component.

<html>
<body>
<div>
<p>some stuff</p>
<div id="stickyComponent" style="padding:10px; width:175px; height:40px; background-color:#00235b; position:fixed; bottom:0; right:0; border-radius: 5px;text-align: center;"><a href="https://dogged-builder-8256.ck.page/e433617a90" ><span style="color:white;">Sticky Component!</span></a></div>
</div>
</body>
</html>

I was trying to add a script to make the sticky component disappear when the user has scrolled to the bottom of the page. But, I keep getting stuck. I am just not certain how to calculate the scroll position relative to the sticky component dynamically. I realize there is a property for scrollTop and scrollLeft, but not scrollBottom or scrollRight. Note: the script element should be placed within the <body> tag

Here is my javascript

<script>
 const sticky = document.querySelector("#stickyComponent");
    const body = document.querySelector('body');
    
    window.addEventListener("scroll", event => {
      
         if (body.scrollHeight <= 0){
            sticky.style.display = "none";
         } else {
            sticky.style.display = "block";
         }
    })
  </script>
Paul T. Rykiel
  • 1,177
  • 6
  • 26
  • 48

1 Answers1

1

You can customize the condition below to fit your specification, simply adjust 100 which is the distance from the bottom. Hide the element as soon as it reaches below that distance and show the element if is above that distance from the bottom.

(window.innerHeight + window.scrollY) >= document.body.offsetHeight - 100

Example:

<html>
  <body>
    <div>
      <p>some stuff</p>
      <div style="height:1000px;"></div>
      <div id="stickyComponent" style="padding:10px; width:175px; height:40px; background-color:#00235b; position:fixed; bottom:0; right:0; border-radius: 5px;text-align: center;">
        <a href="https://dogged-builder-8256.ck.page/e433617a90">
          <span style="color:white;">Sticky Component!</span>
        </a>
      </div>
    </div>
  </body>
  <script>
    window.onscroll = function(ev) {
      var elem = document.getElementById('stickyComponent');
      if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 100) {
        elem.style.display = 'none'; // hide
      }
      else elem.style.display = 'block';
    };
  </script>
</html>
Ibrahim Timimi
  • 2,656
  • 5
  • 19
  • 31