I'm trying to implement something like navigation, when clicking on the elements of which below will drop out a sub-list consisting of several links.

There is such a JS code:

(function() { var links = document.querySelectorAll('.nav--link-select'); var subLists = document.querySelectorAll('.nav__sub-list'); var navItems = document.querySelectorAll('.nav--item-select'); for (var i = 0; i < links.length; i++) { links[i].addEventListener('click', showSubList(i),false); } function showSubList(i){ return function (evt) { // ΠΏΡ€ΠΈ ΠΊΠ»ΠΈΠΊΠ΅ Π½Π° ссылку Π·Π°ΠΊΡ€Ρ‹Π²Π°Π΅ΠΌ всС ΠΎΡ‚ΠΊΡ€Ρ‹Ρ‚Ρ‹Π΅ подсписки for (var j = 0; j < subLists.length; j++) { subLists[j].classList.remove('nav--sub-show'); links[j].classList.remove('nav--link-after'); navItems[j].classList.remove('nav--item-selected'); } evt.stopPropagation(); evt.preventDefault(); // console.log(i); // ΠΏΡ€ΠΈ ΠΊΠ»ΠΈΠΊΠ΅ Π½Π° ссылку ΠΎΡ‚ΠΊΡ€Ρ‹Π²Π°Π΅ΠΌ ΡΠΎΠΎΡ‚Π²Π΅Ρ‚ΡΡ‚Π²ΡƒΡŽΡ‰ΠΈΠΉ подсписок subLists[i].classList.add('nav--sub-show'); links[i].classList.add('nav--link-after'); navItems[i].classList.add('nav--item-selected'); }; }; // ΠΏΡ€ΠΈ ΠΊΠ»ΠΈΠΊΠ΅ ΠΏΠΎ ΠΎΠΊΠ½Ρƒ Π·Π°ΠΊΡ€Ρ‹Π²Π°Π΅ΠΌ всС подсписки document.onclick = function(evt) { for (var k = 0; k < links.length; k++) { subLists[k].classList.remove('nav--sub-show'); links[k].classList.remove('nav--link-after'); navItems[k].classList.remove('nav--item-selected'); } } })(); 

Here is the link to Codepen .

When clicking on the .nav--link-select links .nav--link-select 1, 2 and 4, they add the nav--link-after class nav--link-after , which changes the appearance of the pseudo-element (arrow). And the .nav__sub-list falls out by adding the class nav--sub-show .

Also, when a new sub-list opens, all those that were before it are closed; when clicking on any other window element, the sub-list also closes.

I do not understand how to implement it so that when you click on a link with an open sublist, it closes?

    1 answer 1

    To do this, you need to save the state subscription. Get an array of states for each subscription, which will change as you click on the corresponding subscriptions. Initially all states are off

     var flags = []; 

    After that you click on the subscriptions and there an event occurs in which you need to check the status of the subscription before adding classes to it.

     if (!flags[i]) { subLists[i].classList.add('nav--sub-show'); links[i].classList.add('nav--link-after'); navItems[i].classList.add('nav--item-selected'); } 

    Then, when classes are defined, we simply change the status of the subscription to the opposite.

     flags[i] = !flags[i]; 

    It's all. Next, look and enjoy.

    • Thank you very much for your answer, everything works fine. - Dmitry Ivantsov