Udoro

Add active class to current nav item

May 14th, 2021 (edited)
722
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 1.39 KB | None | 0 0
  1. ADD ACTIVE CLASS FOR SIMPLE ELEMENT
  2. jQuery(document).ready(function(){
  3.   jQuery('li a').click(function(){
  4.     jQuery('li a').removeClass("active");
  5.     jQuery(this).addClass("active");
  6. });
  7. });
  8.  
  9.  
  10.  
  11. ADD ACTIVE CLASS FOR LINKS THAT RELOADS PAGE
  12.  
  13.  
  14. jQuery(document).ready(function () {
  15.   const $links = jQuery('.gallery-link');
  16.   jQuery.each($links, function (index, link) {
  17.     if (link.href == document.URL) {
  18.       jQuery(this).addClass('active');
  19.     }
  20.   });
  21. });
  22.  
  23.  
  24. ADD ACTIVE CLASS FOR ONE PAGE NAV
  25.  
  26. const sections = document.querySelectorAll('.anchor-sections')
  27.  
  28.  
  29.  
  30.  
  31. function scrollActive(){
  32.  
  33.     const scrollY = window.pageYOffset
  34.  
  35.     sections.forEach(section => {
  36.         const sectionHeight = section.offsetHeight,
  37.               sectionTop = section.offsetTop - 150,
  38.               sectionId = section.getAttribute('id')
  39.  
  40.        
  41.  
  42.         if(scrollY > sectionTop && scrollY <= sectionTop + sectionHeight){
  43.  
  44.             document.querySelector(' .menu-side-nav-container a[href*=' + sectionId + ']').classList.add('active')
  45.         }else{
  46.             document.querySelector(' .menu-side-nav-container a[href*=' + sectionId + ']').classList.remove('active')
  47.         }
  48.        
  49.            
  50.        
  51.        
  52.     })
  53.  
  54.  
  55. }
  56.  
  57.  
  58. window.addEventListener('scroll', scrollActive)
  59.  
  60. //select first nav item via attribute
  61. const firstNav = document.querySelector('[title="cool link one"]');
  62.  
  63. //add active class to firt nav item
  64. firstNav.classList.add('active');
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
Add Comment
Please, Sign In to add comment