How to Create a Programmatic JavaScript Tooltip

Follow me!

If you like this article, go ahead and follow me on Twitter:

Follow @getButterfly

Here’s a short tutorial on how to create a programmatic JavaScript tooltip. I needed this feature to recreate a product tour without using a bloated library. I call it a TourTip.

The HTML structure is pretty simple:

<ul>
    <li class="e1">First element</li>
    <li class="e2">Second element</li>
    <li class="e3">Third element</li>
</ul>

The CSS is also pretty simple:

.tourtip {
    position: absolute;
    top: 32px;
    display: none;
    background-color: #333333;
    z-index: 3;
    padding: 8px;
    font-size: 14px;
    color: #ffffff;
    line-height: 1.35;
    min-width: 256px;
    border-radius: 3px;
}
.tourtip.tourtip--on {
    display: block;
}

And here’s the JavaScript:

function showTourtip(element, tip) {
  if (document.querySelector(element)) {
    if (localStorage.getItem('tourtip-1') != 1) {

      var element = document.querySelector(element);

      // Check if tourtip has already been attached
      if (!element.querySelector('.tourtip')) {
        element.innerHTML += '<div class="tourtip">' + tip + '</div>';
      }
      var elementTourtip = element.querySelector('.tourtip');

      elementTourtip.classList.add('tourtip--on');
      elementTourtip.addEventListener('click', function() {
        this.classList.remove('tourtip--on');
        localStorage.setItem('tourtip-1', 1);;
      });
    }
  }
}

document.querySelector('*').addEventListener('click', function (event) {
    showTourtip('li.e1', "Yaaaaay, I'm a programmatic tooltip!");
});

Note that a tourtip-1 will be set to 1 in localStorage, so if you need to test this, make sure you delete it before trying again (or comment the localStorage.getItem() line in the code above).

Here’s a Codepen demo.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

👋 Added by Ciprian on Wednesday, July 17, 2019 in Blog, JavaScript. Last modified on Wednesday, July 17, 2019.

Contribute!

Contribute to this article by sharing your opinion on Twitter:

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started
Privacy Policy