Advertisement
Udoro

Active state on one page navigation JS

Apr 12th, 2022
1,766
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. window.addEventListener('DOMContentLoaded', () => {
  2.  
  3.     const sections = document.querySelectorAll('.anchor-section');
  4.  
  5.  
  6.  
  7.  
  8.  
  9.     function scrollActive(){
  10.  
  11. //get vertical scroll distance
  12.         const scrollY = window.pageYOffset;
  13.  
  14.         sections.forEach(section => {
  15.             var sectionHeight = section.offsetHeight;
  16.             var sectionTop = section.offsetTop - 150;
  17.             var sectionId = section.getAttribute('id');
  18.  
  19.             var anchor = document.querySelector('#split_menu a[href*=' + sectionId + ']')
  20.  
  21.  
  22.             if(scrollY > sectionTop && scrollY <= sectionTop + sectionHeight){
  23.  
  24.  
  25. // add active class to link item that corresponds to the section visible in viewport. whichever anchor section satisfies the condition above, it's going to grab the link anchor for that section and add active class to it
  26.  
  27.                 anchor.classList.add('active');
  28.             }else{
  29.                 anchor.classList.remove('active');
  30.             }
  31.  
  32.  
  33.  
  34.  
  35.         });
  36.  
  37.  
  38.     }
  39.  
  40.  
  41.     window.addEventListener('scroll', scrollActive);
  42.  
  43.  
  44.  
  45.  
  46. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement