Recipe 13.7

Positioning a Popover Relative to an Element

You can get the reference element’s position by calling getBoundingClientRect on it, and use the top or bottom offset to position the popover appropriately.

Note that popover content is placed in the top layer. This means that even with position: absolute, the popover element is positioned relative to the viewport, even if the element with the popover element is inside another element with position: relative.

Demo

This is popover content, anchored to the trigger button.

Code

JavaScript
const popover = document.querySelector('#popover');
const trigger = document.querySelector('#trigger');

popover.addEventListener('toggle', event => {
  // Update the position if the popover is being opened
  if (event.newState === 'open') {
    // Find the position of the trigger element
    const triggerRect = trigger.getBoundingClientRect();

    // Since the popover is positioned relative to the viewport,
    // you need to account for the scroll offset.
    popover.style.top = `${triggerRect.bottom + window.scrollY}px`;
    popover.style.left = `${triggerRect.left}px`;
  }
});
HTML
<style>
  #popover {
    margin: 0;
    margin-top: 1em;
    position: absolute;
  }
</style>

<button class="btn btn-primary" id="trigger" popovertarget="popover">Show Popover</button>
<div id="popover" popover>This is popover content, anchored to the trigger button.</div>
Web API Cookbook
Joe Attardi