Create beautiful tooltips with Popper.js/Tooltip.js

March 06, 2018 0 Comments

Create beautiful tooltips with Popper.js/Tooltip.js



Nowadays web development heavily focuses on constantly improving user experience, while websites are being more beautiful and interactive. One of the ways to display additional information or guide user through the browsing journey are tooltips.

Most of the popular ways to display a tooltip are focused around pulling in additional libraries or frameworks that depend on other libraries, have their styling (if included) and their dependencies, which will increase your app size and add things you probably don’t need.

There comes Popper.js, a very simple and powerful library made for creating tooltips, popovers and all the things you need to show, hide and display relative to another element. According to bundlephobia it’s just 6.7kB!

While Popper.js is just a library, its author already came across community needs and released its actual tooltip-making implementation – Tooltip.js – ready to be used on your website.

Popper.js key features:

  • Automatically positions itself
  • Dead simple API
  • Light (6kB)
  • Works with major frameworks (Angular, React, Vue)
  • Written in ES6
  • Well tested
  • Stays in the viewport when you scroll or resize your window

Popper.js example usage

You can add through npm:

npm install popper.js --save

or include from CDN:

<script src=""></script>

After installation, its minimal amount of code to see the effect is shown below:

var popper = new Popper( document.querySelector('.button'), document.querySelector('.popper') );

where first argument is a reference to the element which your popper needs to be positioned to, and the second is the actual popper wrapper.

More practical example – with Tooltip.js

As I mentioned earlier, Popper.js author came with a ready to implement solution to create tooltips – Tooltip.js

Let’s assume we have a modal with product description and some action buttons:

We have a task to add a tooltip on the button hover showing some additional message to the user.

Code of the button looks like following:

<button class="button is-success">Add to basket</button>

It’s just a html button with some CSS classes. All we need to do to add a very basic tooltip to it is:

Include Tooltip and Popper script files:

<script src=""></script> <script src=""></script>

Add tooltip message somewhere – I’ll use data attribute:

<button class="button is-success" data-tooltip="Only $5 one-time payment!">Add to basket</button>

And a little bit of JavaScript:

document.addEventListener('DOMContentLoaded',function(){ var trigger = document.getElementsByClassName("is-success")[0]; var instance = new Tooltip(trigger,{ title: trigger.getAttribute('data-tooltip'), trigger: "hover", }); });

In the example above we are showing the tooltip on the button hover and the final thing will look like this:

Happy coding! 🙂

Tag cloud