brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: the HTML popover attribute gives you a dropdown with zero JavaScript

Html
~/tips/tip-html-popover-attribute

cat ~/tips/tip-html-popover-attribute.md

Makes a menu or tooltip that opens and closes from a button, without writing JavaScript.

For years every small dropdown meant a bit of JavaScript to open it, close it and catch clicks outside it. Browsers do that themselves now.

<button popovertarget="menu">Menu</button>
<div id="menu" popover>
  <a href="/tips/">Tips</a>
  <a href="/guides/">Guides</a>
</div>

The popover attribute hides the element. The button with popovertarget toggles it, and you need nothing else for a working menu.

A plain popover is the same as popover="auto", and that type can be light dismissed: a click outside it or the Esc key closes it, and opening one auto popover closes the others. If you want it to stay open until the user clicks the button again, use popover="manual". With popovertargetaction on the button you can make a button that only shows (show) or only hides (hide) it, instead of toggling.

The open popover is drawn in the top layer, so there is no z-index fight with the rest of the page.

Caveat: a popover is never modal. The rest of the page stays clickable. For a real dialog that blocks the page, use <dialog>. MDN lists the attribute as widely available since April 2024, so I’d use it without a fallback on a normal site. For a site that has to support old browsers, I’d keep a small script around.

Further reading: MDN: popover attribute, MDN: Popover API

More Html tips import { format } from "dates"; width="640" height="360" poster="demo.jpg"> The HTML optgroup element puts headings inside a long dropdown srclang="en" label="English" default> An HTML noindex meta tag keeps one page out of search results All Html tips (14) All topics

Link