getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2019
getButterfly

How to Create a Programmatic JavaScript Tooltip

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.

Added by Ciprian on Wednesday, July 17, 2019 in Blog, JavaScript

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.


Privacy Policy