To begin, we target all navigation links within the WordPress theme using JavaScript. These links typically have the class .nav-link and represent the various sections of the website.

We then attach a click event listener to each navigation link. When a link is clicked, we prevent its default behavior (i.e., navigating to a new page), retrieve the ID of the target section from the link’s href attribute, locate the corresponding section element, and smoothly scroll to it using the scrollIntoView() method.

Next, we add a scroll event listener to the window. As the user scrolls, we dynamically update the navigation menu to reflect the active section of the page. This is achieved by comparing the current scroll position with the positions of each section. If the current position falls within a section’s range, we add the class .active to the corresponding navigation link and remove it from others.

<script>
// Get all navigation links
const navLinks = document.querySelectorAll('.nav-link');

// Loop through each link and add click event listener
navLinks.forEach(link => {
  link.addEventListener('click', event => {
    event.preventDefault(); // Prevent default link behavior
    const targetId = link.getAttribute('href'); // Get target section id
    const targetSection = document.querySelector(targetId); // Get target section element
    targetSection.scrollIntoView({ behavior: "smooth" }); // Scroll to target section
  });
});

// Add scroll event listener to window
window.addEventListener('scroll', () => {
  const currentPosition = window.pageYOffset; // Get current scroll position
  const sections = document.querySelectorAll('.section'); // Get all sections
  sections.forEach(section => {
    const sectionTop = section.offsetTop - 50; // Get section top position (offsetTop)
    const sectionBottom = sectionTop + section.offsetHeight; // Get section bottom position
    if (currentPosition >= sectionTop && currentPosition < sectionBottom) {
      // Add active class to corresponding navigation link
      navLinks.forEach(link => {
        link.classList.remove('active');
        if (link.getAttribute('href') === `#${section.id}`) {
          link.classList.add('active');
        }
      });
    }
  });
});
</script>
Watch the video tutorial