[InnoJation] Nav Bar Highlighter Bug Fix

·

1 min read

[InnoJation] Nav Bar Highlighter Bug Fix

Problem

This article is about how I solved problem with my portfolio website’s nav bar. The nav bar should highlight a correspond section when the user is on that section. Other sections worked properly, but the VISION section did not.

Original code:

let links = gsap.utils.toArray(".anchor");

links.forEach((link) => {
  let element = document.querySelector(link.getAttribute("href"));

  linkST = ScrollTrigger.create({
    trigger: element,
    start: "top top",
    markers: true,
  });

  ScrollTrigger.create({
    trigger: element,
    start: "top top",
    end: "bottom center",
    onToggle: (self) => setActive(link),
    markers: false,
  });

  link.addEventListener("click", (e) => {
    e.preventDefault();
    gsap.to(window, { duration: 1, scrollTo: linkST.start, overwrite: "auto" });
  });
});

function setActive(link) {
  links.forEach((el) => el.classList.remove("active"));
  link.classList.add("active");
}

My approach was to remove 'active’ class when the scroll trigger meets the current element’s end, and then add ‘active’ to the next element when the scroll trigger meets the start of the next section.


Solution

function setActive(link) {
  link.classList.toggle("active");
}

Simply, I changed add & remove to classList.toggle. classList.toggle removes ‘active’, otherwise adds it.