I’m trying to use HTML’s native popover. I’ve tried using the following JavaScript to toggle the popover on / off.
HTML
<div>
<button onclick="handlePopover(event, 'popover-1')">+</button>
<aside id="popover-1" popover="">
<p>My Test</p>
</aside>
</div>
JavaScript
function handlePopover(event, id) {
// Identify the first popover element with the given id
const popover = document.getElementById(id)
// Exit early if no matching popover was found
if (!popover) return
// Get the coordinates of the clicked button
let rect = event.target.getBoundingClientRect()
// Modify the coordinates of the popover
popover.style.left = rect.left + 10 + "px"
popover.style.top = rect.top + 10 + "px"
// Toggle the display state
popover.togglePopover()
}
The popover toggles on correctly, and it is positioned correctly. However, it does not toggle off when I click the button a second (or third, or fourth..) time. Note however that the popover does disappear if I click outside the popover area AND not on top the button.
How do I hide the popover when the button is clicked a second time?
>Solution :
Without Custom event handler
You can do it easily using popovertarget attribute
<div>
<button popovertarget="popover-1">+</button>
<aside id="popover-1" popover>
<p>My Test</p>
</aside>
</div>
With Custom Event handler
Using manual popover state
If you want to use a custom event for this use following with popover="manual"
<aside id="popover-1" popover="manual">
<p>My Test</p>
</aside>