imcrazytwkr

Floating header in JS

Jun 8th, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const header = document.getElementById('floating-header');
  2. const title = document.getElementById('post-full-title');
  3. const eventParams = { passive: true };
  4.  
  5. let lastScrollY = window.scrollY;
  6. let ticking = false;
  7.  
  8. function requestTick() {
  9.   if (ticking) return;
  10.   requestAnimationFrame(update);
  11.   ticking = true;
  12. }
  13.  
  14. function update() {
  15.   // show/hide floating header
  16.   if (title.getBoundingClientRect().bottom < 0) {
  17.     header.classList.add('floating-active');
  18.   } else {
  19.     header.classList.remove('floating-active');
  20.   }
  21.  
  22.   ticking = false;
  23. }
  24.  
  25. window.addEventListener('scroll', onScroll, eventParams);
  26. function onScroll() {
  27.   lastScrollY = window.scrollY;
  28.   requestTick();
  29. }
  30.  
  31. window.addEventListener('resize', requestTick, eventParams);
  32. update();
Advertisement
Add Comment
Please, Sign In to add comment