Search code examples
csselementhiddensticky

CSS - How to hide an element based on position within page?


I have a sticky element I've setup for a button on mobile devices. This is the code:

.sticky-btn {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
}

Works great but I don't want the button to show when the user is at the very top of the page. It would be perfect if it only appeared after you scrolled down say 20-30 pixels. Is it possible to accomplish this in CSS somehow?

Thanks!


Solution

  • Brian Preston. Unfortunately, we can't do this using only CSS. We should Javascript to add "sticky" class to sticky button and toggle button using that class.

    .sticky-btn {
      position: fixed;
      bottom: 20px;
      left: 50%;
      opacity: 0;
      visibility: hidden;
      pointer-events: none;
      transform: translateX(-50%);
      transition: all .3s ease-in-out;
    }
    .sticky-btn.sticky {
      opacity: 1;
      visibility: visible;
      pointer-events: all;
    }
    

    And JS code should be like this.

    document.addEventListener('DOMContentLoaded', function () {
        var scrollPosition = window.scrollY;
        var stickyBtn = document.querySelector('.sticky-btn');
        window.addEventListener('scroll', function() {
    
            scrollPosition = window.scrollY;
        
            if (scrollPosition >= 30) {
                stickyBtn.classList.add('sticky');
            } else {
                stickyBtn.classList.remove('sticky');
            }
        });
    
    });
    

    Hope this helps. Happy coding ~ :)