JSFiddle - React, Tailwind, and code Playground
by LuckyCat
HTML
<div id="stickymenuwrapper" class="stickymenuwrapper">
<p>Click a triangle to open the sub-menu. Click it again to close the sub-menu or click the other triangle to open its menu and close the first. Clicking a triangle on the next level down will leave the top level open, but its siblings work in the same
way. Clicking outside the menu but inside this box will also close the menu. The CSS for this layout is not finished and is not intended for narrow screens. I'm aware that the second triangle will overflow the pink background on a very narrow view.
Please ignore that. </p>
<div class="hmenu">
<ul id="menucontent" class="navbar">
<li class="item-103 deeper parent linked">
<a href="/">ITEM 1</a>
<button class="btn-level-1 btn-level linked" type="button" name="btn-103"></button>
<ul class="level-1 not-separator">
<li class="item-104">
<a href="/">About us</a>
</li>
<li class="item-107 divider deeper parent separator">
<a class="btn-level-2 btn-level" type="button">Level 2 separator</a>
<ul class="level-2 separator">
<li class="item-108">
<a class="btn-level-3 btn-level" type="button">Level 3 separator</a>
<ul class="level-2 separator">
<li class="item-108">
<a href="/">Lower article 22</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="item-141 deeper parent linked">
<a class="btn-level-2 btn-level heading" type="button">Menu heading</a>
<ul class="level-2 menu-heading">
<li class="item-142">
<a href="/">Article under menu heading</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="item-122 divider deeper parent">
<a class="btn-level-1" type="button">ITEM...
JavaScript
for (const selector of [".btn-level"]) {
const buttons = [...document.querySelectorAll(selector)];
for (const button of buttons) {
button.addEventListener('click', () => {
buttons.filter(b => b !== button).forEach(b => {
b.classList.remove('opened');
});
button.classList.toggle('opened');
});
}
}
document.body.addEventListener('click', (e) => {
if (!e.target.closest('#menucontent')) {
// If click was outside of menu, close menu:
document.querySelector('.opened')?.classList.remove('opened');
}
});