Popover API: The Secret to Easy and Effective Popovers

Popover API: The Secret to Easy and Effective Popovers

Lets learn about Popover API which makes popovers child's play

Popovers are a convenient and versatile way to display information or dialogs about elements, especially when space is limited. But creating them can be a headache, but no more the Popover API handles everything for you, including opening and closing, accessibility, keyboard binding etc.

Popover API

It all starts with a single attribute popover which we have to put on any element we want to make popover of.

Let's learn 3 simple steps to create your first popover

  1. Add popover attribute to the element which you want to make popover

  2. assign an id to it

  3. create a button that you want to work as a trigger and assign a popovertarget attribute with a value equal to the id of the popover element and that's it!!

<!--trigger-->
<button type="button" popovertarget="popover-element">show it</button>
<!--popover-->
<div id="popover-element" popover>
this is over first popover
</div>

Manual Popovers

Up until this point we have created automatic popovers which will be closed if we click anywhere outside it, but we can also manually control this opening and closing of it and disable default behavior using popover=manual

let's learn how we can implement it

  1. add popover=manual attribute to the element which you want to make popover of

  2. assign an id to it

  3. create a button that you want as show button and add 2 attributes popovertarget equals id of the popover element and popovertargetaction = show

  4. create another button that you want as hide button and add 2 attributes popovertarget equals id of the popover element and popovertargetaction = hide

      <div id="popover-manual" popover="manual">
       <button popovertargetaction="hide" 
        popovertarget="popover-manual">x</button>
       <p>this is manual popover</p>
       <p>click on x button to close it</p>
     </div>
     <button type="button" 
     popovertarget="popover-manual" 
     popovertargetaction="show"> open it </button>
    

you can play with it in the following playground and for more information refer to this article

Pitfall

It works on Chrome, Edge and Safari as of now

Thanks for reading.