How to change the class of several items and how to make the navbar update according to the page scroll?

23 views Asked by At

This is for a navbar. The "active" class makes the background of the item in the navbar become darker. And yes, I made the navbar with "div" instead of "ul".

This code of mine is an attempt, whenever an item in the navbar is selected (and its background is made darker), the other selected items pass their class to "unactive".

The code works perfectly when I don't try the "unactive" part, but doing so it just makes everything I click active.

I would like help with this.

Furthermore, I would like to know how to make the navbar update the parts that are selected according to where I am on the page. Ex.: I am in the voting section and I move to the sponsors section. How do I make the navbar automatically select the session I'm in?

thanks for any help!

HTML

<div class="navigation-header" id="navigation-header">
  <a href="#voting-section" onclick="closeSidebar()" class="active">Votação</a>
  <a href="#sponsors-section" onclick="closeSidebar()">Patrocinadores</a>
  <a href="#socialmedia-section" onclick="closeSidebar()">Redes Sociais</a>
  <a href="#credits-section" onclick="closeSidebar()">Créditos</a>
</div>

JAVASCRIPT

var navbars = document
  .querySelector(".navigation-header")
  .querySelectorAll("a");

navbars.forEach(function (item) {
  item.addEventListener("click", function (e) {
    let classe = this.getAttribute("class");
    if (classe != "active") {
      navbars.forEach(function (navitem) {
        let classe = this.getAttribute("class");
        if (classe === "active") {
          this.classList.remove(classe);
          this.classList.add("unactive");
        }
      });

      this.classList.remove(classe);
      this.classList.add("active");
    }
  });
});

1

There are 1 answers

0
amel On

I don't know if I understood well what you need, Check this please and tell me:

var navbars = document
  .querySelector(".navigation-header")
  .querySelectorAll("a");

navbars.forEach(function (item) {
  item.addEventListener("click", function (e) {
    let classe = e.target.getAttribute("class");
    if (classe != "active") {
      navbars.forEach(function (navitem) {
        let classe = navitem.getAttribute("class");
        if (classe == "active") {
          navitem.classList.remove(classe);
          navitem.classList.add("unactive");
        }
      });

      e.target.classList.remove(classe);
      e.target.classList.add("active");
    }
  });
});
a.active {
  background: #ee0;
}
<div class="navigation-header" id="navigation-header">
  <a href="#voting-section" class="active">Votação</a>
  <a href="#sponsors-section" class="unactive">Patrocinadores</a>
  <a href="#socialmedia-section" class="unactive">Redes Sociais</a>
  <a href="#credits-section" class="unactive">Créditos</a>
</div>