Skip to content
Advertisement

Setting up an .active class to a dynamically created link JS

I built a navbar a few weeks back and just realised I did not set an .active class on it. Now, I built the navbar and the links dynamically in JS and would now like to give whichever one is active the according CSS.

This is how I built the navbar in JS:

let womensNav = document.createElement("ul");
womensNav.classList.add("womensNav");

const el1 = document.createElement("li");
el1.innerHTML = "<a>Jeans</a>";
el1.addEventListener("click", (e) => {
      document.location.href =
        "https://www.martadolska.com/product-category/women/womens-jeans";
});

womensNav.appendChild(el1);
document.querySelector(".ast-woocommerce-container").appendChild(womensNav);

I have more than one link, but for this purpose I don’t need to show it all. So now the goal is to build a generic function that gives the active element within the navbar the according class.

document.querySelectorAll("#womensNav li").forEach(function (ele) {
      ele.addEventListener("click", function (e) {
        e.preventDefault();
        document
          .querySelectorAll("#womensNav li a.active")
          .forEach((ele) => ele.classList.remove("active"));
        ele.parentNode.classList.toggle("active");
      });
    });

And this is what my CSS looks like:

.womensNav li a:hover {
  color: var(--main-text-color);
  text-decoration: line-through darkred solid;
}
.womensNav li a::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: 7px;
  left: 0;
  background-color: #b22222;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}
.womensNav li a:hover::before {
  visibility: visible;
  transform: scaleX(1);
}
.womensNav li a:active::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: 10px;
  left: 0;
  background-color: #b22222;
}

// up until this point everything works
.active {
  text-decoration: line-through darkred solid;
}

I am guessing there is something missing/not completely right in the second snippet of the JS code since nothing is happening when my link is active. I get the animation that I would like to get, but then it disappears once the user is redirected to that specific link, so you wouldn’t know which sub-page you are on.

Advertisement

Answer

this is wrong

ele.parentNode.classList.toggle("active");

“ele” is the <li>, you are adding the “active” class to the <ul> via the parentNode, might be better to use the “e” event from the click and use e.target and then try and set the active class on the <a> or use childNode/children to get at your <a>

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement