Udoro

Sticky/Overlay header JS

Feb 5th, 2022 (edited)
1,475
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. window.addEventListener('DOMContentLoaded', () => {
  2.  
  3. const  header = document.querySelector('.header'),
  4.              headerRow = document.querySelector('.header-row'),
  5.              body = document.body
  6. var checkOverlay = false // or true
  7. // (getComputedStyle won't work in Edge, so set the value manually)getComputedStyle(document.documentElement).getPropertyValue ('--overlay-header')  
  8.  
  9. //Check for scroll action
  10.  
  11.     window.addEventListener('scroll', ()=>{
  12.  
  13.         var scrollDistance = 400,
  14. // (getComputedStyle won't work in Edge, so set the value manually) getComputedStyle(document.documentElement).getPropertyValue ('--scroll-distance'),
  15.             checkSticky = true //or false
  16. //(getComputedStyle won't work in Edge, so set the value manually)  getComputedStyle(document.documentElement).getPropertyValue ('--sticky-header')
  17.  
  18.         //add class if scroll distance is less than windows scroll height & --sticky-header is true
  19.  
  20.         header.classList.toggle('sticky', window.scrollY > scrollDistance && checkSticky == 'true' )
  21.         body.classList.toggle('has-sticky', window.scrollY > scrollDistance && checkSticky == 'true')
  22.  
  23.     })   //end scroll action
  24.  
  25.  
  26.  
  27.  
  28.  
  29. //Check if --overaly-header is set to true, add classes else remove classes
  30.  
  31.     if (checkOverlay == 'true') {
  32.                 header.classList.add('overlay')
  33.                 body.ClassList.add('has-overlay')
  34.     } else{
  35.                 header.classList.remove('overlay')
  36.                 body.ClassList.remove('has-overlay')
  37.     }
  38.  
  39.  
  40.  
  41. });
Add Comment
Please, Sign In to add comment