sinanisler logo

Scroll Show Hide, Header, Menu, Depending on the Scroll Direction

with this code you can change css depending on the direction of the scroll. this example is for header but you can do this for any dom

for example on this example I am hiding the header while scrolling down by moving the header -110px up and when moving up it show itself because the .scrolling-down class removed when scrolling up.

add .header-top to your header or menu that’s how the script selects.

<style>
  .header-scrolled  .header-logo img{
    width:160px
   
  }
  .header-scrolled  .header-logo{
    padding:0 !important
  }
  .header-scrolled{
    background:white
  }
  .header-scrolled .header-top-inner{
    height:80px
  }

  .scrolling-down{
    transform:translateY(-110px)
  }
</style>

<script>
  
const header = document.querySelector('.header-top');
let lastScrollPosition = 0;

window.addEventListener('scroll', function() {
    const currentScrollPosition = window.pageYOffset || document.documentElement.scrollTop;
    
    if (currentScrollPosition > header.offsetHeight) {
        header.classList.add('header-scrolled');
    } else {
        header.classList.remove('header-scrolled');
    }
    
    if (currentScrollPosition > lastScrollPosition) {
        header.classList.remove('scrolling-up');
        header.classList.add('scrolling-down');
    } else if (currentScrollPosition < lastScrollPosition) {
        header.classList.remove('scrolling-down');
        header.classList.add('scrolling-up');
    }
    
    lastScrollPosition = currentScrollPosition;
});
  
</script>

Leave the first comment