Using Popper.js for generating tooltips

In web application usually, you need to generate a tooltip that will display an icon, buttons, or something else. most of the people use title attribute or data attribute for that but the position for the tooltip is not fixed. Sometimes it displays on left, right, or even on the content itself. Popper.js is the solution for that. It allows us to create a tooltip and specify the position where it should display.
Visit: https://popper.js.org it contains some examples. we can create a static tooltip, as well as a dynamic tooltip that will adjust based on scroll or content size.

Install
First of all, we need to install it. For npm use below command to install its package.

npm install popper.js --save

Create Content & Tooltip elements
After this we need to create tooltip & content element. However we can update tooltip contents after it. So you can also create empty elements.

<button id="contentElement" class="button">
    Original content
</button>


<div id="tooltipElement" class="tooltip">
    This is Tooltip text. You can also add Rich content!
</div>

Create Popper
We need to create poppers on a DOMContentLoaded event. And toggle its visibility on clicking of the button or focus out of element event.

document.addEventListener('DOMContentLoaded', function () {
    var index = 0;
    var contentElement = $('#contentElement');
    var tooltipElement = $('#tooltipElement');

    tooltipElement.hide();
    contentElement.click(function () {
        tooltipElement.toggle();
        //Position of the popper
        var popper = new Popper(contentElement, tooltipElement, {
            placement: 'right',
            boundariesElement: contentElement.parentNode
        });
    });
});

Click here to download above example as HTML file.

Leave a Reply

Your email address will not be published. Required fields are marked *