Toggle menu when I click on menu one it shows me item two

Asked

Viewed 53 times

0

const itemLinks = document.querySelectorAll('.header-item')
const navHeader = document.querySelectorAll('.nav-menu')

for (let i = 0; i < itemLinks.length; i++) {
    itemLinks[i].addEventListener('click', function(e) {
        for (let i = 0; i < navHeader.length; i++) {
            navHeader[i].classList.toggle('active')
        }
        navHeader[i].classList.remove('active')
    })
}
.nav-menu.active{
    display: block;
}
.nav-menu{
    display: none;
}
<a href="#one" class="header-item header-item--one">menu one</a>
<a href="#two" class="header-item header-item--two">menu two</a> 

<nav class="nav-menu">
    <ul>
        <li>Item one</li>
        <li>Item one</li>
        <li>Item one</li>
    </ul>
</nav>

<nav class="nav-menu">
    <ul>
        <li>Item two</li>
        <li>Item two</li>
        <li>Item two</li>
    </ul>
</nav>

1 answer

0


I believe that this way it resolves:

const itemLinks = document.querySelectorAll('.header-item')
const navHeader = document.querySelectorAll('.nav-menu')

for (let i = 0; i < itemLinks.length; i++) {
    itemLinks[i].addEventListener('click', function(e) {
        // usei uma variável diferente para ficar mais legível e permitir a posterior comparação de indíces
        for (let ii = 0; ii < navHeader.length; ii++) {
          if (ii !== i) // checa para manter o "estado" (classe active) do menu clicado
            navHeader[ii].classList.remove('active')
        }
        navHeader[i].classList.toggle('active'); // com o "estado" mantido, é possível usar toggle
    })
}

Explaining, I removed all states in the loop and then toggle from the clicked menu, making it appear if it is invisible or invisible if visible.

The code snippet below gets confused as the keyword let makes the variable only exists in the scope of the loop for, different from when using var:

for (let i = 0; i < itemLinks.length; i++) {
  • Thanks Anderson thanks Ai bro solved!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.