Table of Contents

Web UI - Popper library (tooltip and popover positioning)

About

popper is a positional library that position tooltips and popovers

popper is now floating-ui 1)

It also makes sure that the positioned element never end up off screen or cropped by an overflow. (Resizing your browser will re-position the positioned elements)

Example

Tooltip

<div id="tooltip" role="tooltip" >
    <h3>A tooltip</h3
    <p>Example of a tooltip on mouseenter and mouseleave</p>
</div>
<button id="button" aria-describedby="tooltip">Button</button>
#tooltip {
        background: #333;
        color: white;
        padding: 4px 8px;
        font-size: 13px;
        border-radius: 4px;
}
const button = document.querySelector('#button');
const tooltip = document.querySelector('#tooltip');
const popperInstance = Popper.createPopper(button, tooltip,  { placement: "bottom-start" });
#tooltip {
  /* Not displayed at first */
  display: none;
}

#tooltip[data-show] {
  display: block;
}
function show() {
  tooltip.setAttribute('data-show', '');

  // We need to tell Popper to update the tooltip position
  // after we show the tooltip, otherwise it will be incorrect
  popperInstance.update();
}

function hide() {
  tooltip.removeAttribute('data-show');
}

const showEvents = ['mouseenter'];
const hideEvents = ['mouseleave'];

showEvents.forEach((event) => {
  button.addEventListener(event, show);
});

hideEvents.forEach((event) => {
  button.addEventListener(event, hide);
});

Popover

<div id="popover" role="popover" >
    <ul>
      <li>First item</li>
      <li>Second item</li>  
    </ul>
</div>
<input type="text" id="search-box" aria-describedby="searchbox" />
#popover {
        background: #333;
        color: white;
        padding: 4px 8px;
        font-size: 13px;
        border-radius: 4px;
}
const searchBox = document.querySelector('#search-box');
const popover = document.querySelector('#popover');
const popperInstance = Popper.createPopper(searchBox , popover,  { placement: "bottom-start" });
#popover{
    display: none; /* Not displayed at first */
}

#popover[data-show] {
  display: block;
}
function show() {
  popover.setAttribute('data-show', '');

  // We need to tell Popper to update the tooltip position
  // after we show the tooltip, otherwise it will be incorrect
  popperInstance.update();
}

function hide() {
  popover.removeAttribute('data-show');
}

const showEvents = ['focus'];
const hideEvents = ['blur'];

showEvents.forEach((event) => {
  searchBox.addEventListener(event, show);
});

hideEvents.forEach((event) => {
  searchBox.addEventListener(event, hide);
});