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
- The content of the tooltip
<div id="tooltip" role="tooltip" >
<h3>A tooltip</h3
<p>Example of a tooltip on mouseenter and mouseleave</p>
</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;
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, { placement: "bottom-start" });
#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 = ['mouseenter'];
const hideEvents = ['mouseleave'];
showEvents.forEach((event) => {
button.addEventListener(event, show);
});
hideEvents.forEach((event) => {
button.addEventListener(event, hide);
});
- Output:
- mouse over (mouseenter) on the button to show the tooltip
- leave (mouseleave) the button to hide the tooltip
Popover
- The content of the popover
<div id="popover" role="popover" >
<ul>
<li>First item</li>
<li>Second item</li>
</ul>
</div>
- The input that will trigger the popover
<input type="text" id="search-box" aria-describedby="searchbox" />
- The styling of the popover
#popover {
background: #333;
color: white;
padding: 4px 8px;
font-size: 13px;
border-radius: 4px;
}
- The instance
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;
}
- Show and hide Javascript
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);
});