Web UI - Popper library (tooltip and popover positioning)

About

popper is a positional library that position tooltips and popovers

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

  • The content of the tooltip
<div id="tooltip" role="tooltip" >
    <p><b>A tooltip</b></p>
    <ul>
      <li>First item</li>
      <li>Second item</li>  
    </ul>
</div>
  • The button that will trigger the tooltip
<button id="button" aria-describedby="tooltip">Button</button>
  • The styling of the tooltip
#tooltip {
        background: #333;
        color: white;
        font-weight: bold;
        padding: 4px 8px;
        font-size: 13px;
        border-radius: 4px;
}
  • The instance
const button = document.querySelector('#button');
const tooltip = document.querySelector('#tooltip');
const popperInstance = Popper.createPopper(button, tooltip, 
	{
	  modifiers: [
		{
		  name: 'offset',
		  options: {
			offset: [0, 8],
		  },
		},
	  ]
	}
);
#tooltip {
  /* Not displayed at first */
  display: none;
}

#tooltip[data-show] {
  display: block;
}
  • Show and hide Javascript
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 = ['focus'];
const hideEvents = ['blur'];

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

hideEvents.forEach((event) => {
  button.addEventListener(event, hide);
});
  • Output:
    • click on the button to get focus
    • and click on the right to blur (loose focus)

Powered by ComboStrap