One page links per Kadence

function highlightAnchorLinks() {
  // Get the menu elements
  const primaryMenu = document.getElementById('primary-menu');
  const mobileMenu = document.getElementById('mobile-menu');
  // Get all anchor links within the primary menu
  const primaryAnchorLinks = primaryMenu.querySelectorAll('li > a[href*="#"]');
  // Get all anchor links within the mobile menu
  const mobileAnchorLinks = mobileMenu.querySelectorAll('li > a[href*="#"]');
  // Function to extract the target ID from the href attribute
  const extractTargetId = (href) => {
    const hashIndex = href.indexOf('#');
    return hashIndex !== -1 ? href.substring(hashIndex + 1) : null;
  };
  // Create an intersection observer instance for the primary menu
  const primaryObserver = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      const targetId = entry.target.getAttribute('id');
      const listItem = primaryMenu.querySelector(`li > a[href$="#${targetId}"]`).parentNode;
      if (entry.isIntersecting && entry.intersectionRatio >= 0.5) {
        const activeListItem = primaryMenu.querySelector('.current-menu-item');
        if (activeListItem) {
          activeListItem.classList.remove('current-menu-item', 'current_page_item');
        }
        listItem.classList.add('current-menu-item', 'current_page_item');
      } else {
        listItem.classList.remove('current-menu-item', 'current_page_item');
      }
    });
  }, { threshold: [0.5] });
  // Create an intersection observer instance for the mobile menu
  const mobileObserver = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      const targetId = entry.target.getAttribute('id');
      const listItem = mobileMenu.querySelector(`li > a[href$="#${targetId}"]`).parentNode;
      if (entry.isIntersecting && entry.intersectionRatio >= 0.5) {
        const activeListItem = mobileMenu.querySelector('.current-menu-item');
        if (activeListItem) {
          activeListItem.classList.remove('current-menu-item', 'current_page_item');
        }
        listItem.classList.add('current-menu-item', 'current_page_item');
      } else {
        listItem.classList.remove('current-menu-item', 'current_page_item');
      }
    });
  }, { threshold: [0.5] });
  // Observe each section for the primary menu
  primaryAnchorLinks.forEach(anchorLink => {
    const targetId = extractTargetId(anchorLink.getAttribute('href'));
    const section = document.getElementById(targetId);
    if (section) {
      primaryObserver.observe(section);
    }
  });
  // Observe each section for the mobile menu
  mobileAnchorLinks.forEach(anchorLink => {
    const targetId = extractTargetId(anchorLink.getAttribute('href'));
    const section = document.getElementById(targetId);
    if (section) {
      mobileObserver.observe(section);
    }
  });
}
// Call the function when the DOM is fully loaded
document.addEventListener('DOMContentLoaded', highlightAnchorLinks);