Popovers are a great way to provide additional context or information to users without cluttering our web page. HTML makes it easy to implement popovers using the popover attribute, a global attribute common to all HTML elements. Global attributes can be used on all elements, though they may have no effect on some elements.
In the past, creating popovers often required tricky CSS or JavaScript solutions. However, with the introduction of the popover
attribute, this task has become remarkably simpler. Let’s explore how to use this attribute to create popovers and understand their behavior.
In the following example, we’ve added the popover
attribute to a button
. When we click this button we’ll see the popover displaying the text “Welcome to Educative.”
On lines 11–12, an HTML <button>
element is set up with a custom attribute called popovertarget
. This attribute is intended to control the display of the popover associated with the <div>
element having the same id
as specified in the popovertarget
attribute. When the button is clicked, the <div>
element with the matching id
("my-popover"
) is either shown or hidden, revealing or concealing its content, which, in this case, is “Welcome to Educative.”
popover
attributeThe popover
attribute can have the "auto"
(default) or "manual"
values. It’s essential to understand the difference between these states:
Auto: Popovers in the auto
state are hidden by default via display: none
. They can be dismissed by clicking outside the popover area. Usually, only one popover in the auto
state is allowed to be displayed on-screen at a time.
Manual: Popovers in the "manual"
state must always be explicitly hidden or shown. This state is useful for scenarios like nested popovers in menus, where precise control over popover behavior is required.
Go ahead and replace the second line of the code with the following statement:
<div popover="manual" id="my-popover">Welcome to Educative</div>
If you click anywhere else on the screen now, the “Welcome to Educative” text won’t disappear as it did earlier when we had our popover attribute set to "auto"
. The only way to hide the popover element is to actually click the button we used to make it appear.