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.