Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

togglePopover() not opens but doesn't close native HTML popover

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Demo

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading