A dropdown menu built on a non-modal `<dialog>` that closes when you click anywhere outside it.
A dropdown menu opens on click and closes when the user clicks anywhere
outside it. Built on a non-modal <dialog> so it gets keyboard accessibility
and using hyperscript's elsewhere modifier for the click-outside behavior.
<div class="dropdown">
<button _="on click show the next <dialog/> then halt">Account ▾</button>
<dialog class="dropdown-menu"
_="on click elsewhere close me
on keyup[key is 'Escape'] from window close me">
<a>Profile</a>
<a>Settings</a>
<a>Help</a>
<hr>
<a>Sign out</a>
</dialog>
</div>
Three pieces of hyperscript do all the work:
on click show the next <dialog/> then halt on the trigger
button. show calls dialog.show() (non-modal), which leaves the dialog
in the document flow so position: absolute anchors it to its parent. halt stops
the click from bubbling up to document to prevent the on click from elsewhere handler
on the dialog from firing.
on click elsewhere close me on the <dialog>. The elsewhere modifier
is a hyperscript features that listens for the event at the document level and only fires
when the click target is not inside this element. close me closes the dropdown.
on keyup[key is 'Escape'] from window close me adds keyboard dismissal.
Modal dialogs get Esc handling from the browser, but non-modal show() does
not. Easy fix with a bit of hyperscript.