How to hide a menu by clicking on another in JS?

Asked

Viewed 102 times

0

I can’t get when one menu opens the other to close. I tried the following code:

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

for(let i = 0; i < itemLinks.length; i++){
	itemLinks[i].addEventListener('click',mostrarMenu)
}

function mostrarMenu(e){
	console.log(menus)
	for(let i = 0; i < menus.length; i++){

	}
}
<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 Um</li>
        <li>Item Dois</li>
        <li>Item Três</li>
    </ul>
</nav>

<nav class="nav-menu">
    <ul>
        <li>Item Um</li>
        <li>Item Dois</li>
        <li>Item Três</li>
    </ul>
</nav>

  • 1

    Could you elaborate a [mcve] demonstrating the problem? Your code seems to be incomplete and quite confused as to what you want to do.

  • good morningAnderson the code was really confusing hehe, had modified the html and forgot to edit the js.. more like this.. it remains incomplete n can go on already tried more I can only get that by clicking on a link open the menu and after clicking on another it opens at the same time. what I want to do is that when clicked on the other it closes,if you can help me thank hug.

  • Have you tried using jQuery? It provides this type of pre-built functionality. Check out this https://www.w3schools.com/jquery/

1 answer

1


Trying to follow a little the architecture of bootstrap + jQuery, I could do as follows:

var headerItems = document.getElementsByClassName("header-item");

for (var headerItem of headerItems) {
    headerItem.onclick = function(ev) {
        var refItem = document.getElementById(ev.target.getAttribute("data-toggle"));
        var navItems = document.getElementsByClassName("nav-menu");

        for (var navItem of navItems) {
            navItem.classList.add("hidden");
        }
        refItem.classList.remove("hidden");
    }
}
.hidden {
    display: none
}
<a href="#one" data-toggle="item-1" class="header-item header-item--one">menu one</a>
<a href="#two" data-toggle="item-2" class="header-item header-item--two">menu two</a>

<nav id="item-1" class="nav-menu hidden">
    <ul>
        <li>Item Um1</li>
        <li>Item Dois1</li>
        <li>Item Três1</li>
    </ul>
</nav>

<nav id="item-2" class="nav-menu hidden">
    <ul>
        <li>Item Um2</li>
        <li>Item Dois2</li>
        <li>Item Três2</li>
    </ul>
</nav>

What happens is that in the headers click event, it removes the class hidden of all elements nav-menu and then just add in what’s inside the data-toggle.

Browser other questions tagged

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