There is a button with a menu

<button class="show-menu" style="display: flex; align-items: center;"> <h3>Помощь</h3> </button> <ul class="menu menu--hide"> <li class="menu__item" style="display: flex; align-items: center;" > <p>Тест</p> </li> <li class="open-record-panel-btn menu__item" style="display: flex; align-items: center;" > <p>Тест2</p> </li> </ul> 

And such a code that hangs an event (hides it opens), but it works when clicked, but with focus. Tell me how to make the button work with the focus, and when you click on another area of ​​the menu, it hides

 var linkBtn = document.querySelector('.show-menu'); if (linkBtn) { linkBtn.addEventListener('click', function(event) { event.preventDefault(); var menuList = document.querySelector('.menu--hide'); if(menuList) { menuList.classList.toggle('menu--show'); } }); } 
  • In fact, it is not very clear what it means to “with focus”. The event "focus" occurs in case if an element is clicked or a keyboard transition is performed using Tab. If the menu works for you on click, it means that it works by focus (it gets focus when clicked). Maybe you mean hover (guidance)? - humster_spb
  • I just need it to be hidden when clicking outside the menu, so focus is required - VoA
  • But it is not hidden in me and is always displayed after clicking on the button - VoA
  • Well, and here Rogatnev Nikita gave you the answer - isn't that what you want? The button opens, when you click outside the menu closes. - humster_spb
  • Clicks on the menu items do not work, because it immediately disappears, but it is necessary to hide only when you click outside the menu ( - VoA

1 answer 1

You can do it all in pure CSS. Codepen: https://codepen.io/rogatnev-nikita/full/wRMExj

 .menu { display: none; } .show-menu:focus + .menu { display: block; } 
 <button class="show-menu"> <h3>Помощь</h3> </button> <ul class="menu"> <li class="menu__item"> <p>Тест</p> </li> <li class="open-record-panel-btn menu__item"> <p>Тест2</p> </li> </ul> 

If you need JS, then track the focus event of the EventListener method

 document.addEventListener('focus', function(event) { /* Ваш код */ }, true); 
  • When I set focus to addEventListener, it doesn’t work, when I click on another area of ​​the menu, I don’t hide - VoA
  • Clicks on the menu items now do not work ( - VoA
  • @VoA then the focus here is nothing to do with, see the answers here ru.stackoverflow.com/questions/140922/… - Rogatnev Nikita