The togglePopover()
method of the HTMLElement
interface toggles a popover element (i.e. one that has a valid popover
attribute) between the hidden and showing states.
When togglePopover()
is called on an element with the popover
attribute:
- A
beforetoggle
event is fired. - The popover toggles between hidden and showing:
- If it was initially showing, it toggles to hidden.
- If it was initially hidden, it toggles to showing.
- A
toggle
event is fired.
true
if the popup is open after the call, and false
otherwise.
None (undefined
) may be returned in older browser versions (see browser compatibility).
See the Popover API examples landing page to access the full collection of MDN popover examples.
This is a slightly modified version of the Toggle Help UI Popover Example. The example toggles a popover on and off by pressing a particular key on the keyboard (when the example window has focus).
The HTML for the example is shown below. This first element defines instructions on how to invoke the popup, which we need because popups are hidden by default.
<p id="instructions">
Press "h" to toggle a help screen (select example window first).
</p>
We then define a <div>
element which is the popup. The actual content doesn't matter, but note that we need the popover
attribute to make the <div>
into a popover so that it is hidden by default (or we could set this element in the JavaScript).
<div id="mypopover" popover>
<h2>Help!</h2>
<p>You can use the following commands to control the app</p>
<ul>
<li>Press <ins>C</ins> to order cheese</li>
<li>Press <ins>T</ins> to order tofu</li>
<li>Press <ins>B</ins> to order bacon</li>
</ul>
</div>
The JavaScript for the example is shown below. First we check whether popovers are supported, and if they aren't we hide the popover div
so that it isn't displayed inline.
const instructions = document.getElementById("instructions");
const popover = document.getElementById("mypopover");
if (!HTMLElement.prototype.hasOwnProperty("popover")) {
popover.innerText = "";
instructions.innerText = "Popovers not supported";
}
If popovers are supported we add a listener for the h
key to be pressed, and use that to trigger opening the popup. We also log whether the popup was open or closed after the call, but only if a true
or false
was returned.
if (HTMLElement.prototype.hasOwnProperty("popover")) {
document.addEventListener("keydown", (event) => {
if (event.key === "h") {
const popupOpened = popover.togglePopover();
if (popupOpened !== undefined) {
instructions.innerText +=
popupOpened === true ? `\nOpened` : `\nClosed`;
}
}
});
}
You can test this out using the live example below.