I’m building a simple menu with a collection of buttons. The first button toggles a class which is use show or hide the following div full of more buttons. That part works.
The tricky part is closing the menu when I click out. From various questions around SO, I get the solution of doing the following:
- Set the
tabindexon the menu container. - Set the focus on the menu container when the menu is opened.
- use
onblurto toggle off the class which opens the menu.
That part also works, but the buttons no longer work.
I’m guessing that the onblur happens first, and that closing the menu prevents the button from firing. If I disable the class toggle, then the button will fire.
I have tried using onclick as well as addEventListener with both true an false. Nothing helps.
Any suggestions on how I can get the button to fire before the menu closes?
let menu = document.querySelector('div#menu');
menu.setAttribute('tabindex',1);
let toggle = menu.querySelector('button#toggle');
toggle.onclick = event => {
toggle.classList.toggle('open');
menu.focus();
};
menu.querySelector('button#apple').onclick = event => {
console.log('apple');
};
menu.querySelector('button#banana').addEventListener('click', event => {
console.log('banana');
}, false);
menu.querySelector('button#cherry').addEventListener('click', event => {
console.log('cherry');
}, true);
// hide when clicked off
menu.onblur = event => {
console.log('byebye');
toggle.classList.toggle('open', false);
};
div#menu {
position: relative;
button#toggle+div {
position: absolute;
display: none;
flex-direction: column;
}
button#toggle.open+div {
display: flex;
}
}
<div id="menu">
<button id="toggle">Things</button>
<div>
<button id="apple">Apple</button>
<button id="banana">Banana</button>
<button id="cherry">Cherry</button>
</div>
</div>
<p>Some stuff</p>
