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?
2
Answers
Demo
Without Custom event handler
You can do it easily using
popovertarget
attributeWith Custom Event handler
Using manual popover state
If you want to use a custom event for this use following with
popover="manual"
you can also do something like this:
a) give your button an id
b) toggle popOver when the button is clicked
underscore’s solution is more concise and clean, so if it covers your needs, it’s the one to pick.