My blog navigation originally toggled the menu with a hidden input + label hack:
<input id="toggle-nav" type="checkbox" hidden />
<div id="nav">
<label for="toggle-nav">Toggle</label>
Menu...
</div>
The for attribute worked, but it was neither semantic nor maintainable. Replacing it with the Popover API keeps everything in HTML — no JavaScript required.
Code Replacement
The task of changing the code was quite simple.
- Use the
buttontag, which actually serves as a button, instead of thelabeltag. - Assign new attributes to the popover target.
- Apply custom styles.
- <input id="toggle-nav" type="checkbox" hidden>
+ <button popovertarget="nav" popoveraction="toggle">Toggle</button>
- <div id="nav">
+ <div id="nav" popover>
- <label for="toggle-nav">Toggle</label>
+ <button popovertarget="nav" popoveraction="toggle">Toggle</button>
Menu...
</div>
+ <style>
+ #nav {
+ /* reset */
+ display: block;
+ padding: unset;
+ }
+ </style>
Additional Features of the Popover API
The Popover API can be implemented using only HTML without external libraries, reducing code dependencies and minimizing code length. This provides significant advantages in terms of code maintainability, allowing for cleaner and more manageable code.
-
Background Blurring: When the popover is activated, the background can be blurred, allowing users to focus solely on the content of the popover. This feature can be easily implemented with pure HTML, adding visual effects without additional scripts.
-
Auto-Close Feature: You can set the popover to automatically close when the user clicks outside of it or presses the ESC key. This can also be implemented using just HTML attributes, completing the functionality without unnecessary JavaScript code.
-
Animation Effects: Animation effects that make the appearance and disappearance of the popover smooth can also be easily applied with HTML, reducing code complexity and making maintenance easier.
The Popover API has broad browser support as of 2024, but verify coverage against your target audience before shipping.