add styled tooltips using vanilla javascript
posted on November 13, 2021, 12:00 am in
Heres how you can add CSS styled tooltips to your webpage without any frameworks.
code
let targets = document.querySelectorAll('*[data-tooltip]');
var createElementEx = function(id, className, innerHTML = '') {
var el = document.createElement('div');
el.id = id;
el.className = className;
el.innerHTML = innerHTML;
return el;
};
targets.forEach(function(elem) {
var uid = '';
// if js is disabled, will have default system 'title' to keep accessibility ...
const title = elem.getAttribute('title');
elem.removeAttribute('title');
elem.addEventListener('mouseenter', function(event) {
var elemRect = elem.getBoundingClientRect();
var top = (elemRect.top),
left = (elemRect.left) - 4;
left += Math.floor(elemRect.width / 2) - 4;
uid = `tooltip-${new Date().getTime()}`;
var newEl = createElementEx(uid, 'tooltip-outer');
var text = createElementEx('', 'tooltip-inner', title);
newEl.appendChild(text);
document.body.appendChild(newEl);
var tooltip = document.getElementById(uid);
var toolRect = tooltip.getBoundingClientRect();
var tooltipWidth = toolRect.width - 18 - 2;
if (top > toolRect.height + 25) {
tooltip.style.top = Math.floor(top - toolRect.height - 8 - 5) + 'px';
tooltip.style.left = Math.floor(left - Math.floor(toolRect.width / 2) + 8) + 'px';
var arrow = createElementEx('', 'tooltip-bottom-arrow');
arrow.style.marginLeft = (tooltipWidth / 2) + 'px';
tooltip.appendChild(arrow)
} else {
tooltip.style.top = Math.floor(elemRect.height + top + 8) + 'px';
tooltip.style.left = Math.floor(left - Math.floor(toolRect.width / 2) + 8) + 'px';
var arrow = createElementEx('', 'tooltip-top-arrow', '');
arrow.style.marginLeft = (tooltipWidth / 2) + 'px';
tooltip.insertBefore(arrow, tooltip.firstChild);
}
if ((left < toolRect.width / 2)) {
var diff = left - (toolRect.width / 2);
tooltip.style.left = Math.floor(left - Math.floor(toolRect.width / 2) + 8 - diff) + 'px';
tooltip.style.marginLeft = ((tooltipWidth / 2) + diff) + 'px';
}
});
elem.addEventListener('mouseleave', function(event) {
var tooltip = document.getElementById(uid);
if (tooltip)
tooltip.parentNode.removeChild(tooltip);
});
});
.tooltip-outer {
position: fixed;
z-index: 999999;
}
.tooltip-inner {
background: #272725;
padding: 10px;
color: #dfdfdf;
font-size: 14px;
border-radius: 3px;
text-align: left;
max-width: 485px;
}
.tooltip-top-arrow, .tooltip-bottom-arrow {
width: 0;
height: 0;
border-left: 8px solid transparent;
border-right: 8px solid transparent;
}
.tooltip-top-arrow {
border-bottom: 8px solid #272725;
}
.tooltip-bottom-arrow {
border-top: 8px solid #272725;
}
strong { color: red; }
<span data-tooltip title="Ex 1, my tooltip text">Ex 1, basic tooltip</span>
<span data-tooltip title="Ex 2, tooltip with embedded <strong>html</strong>">Ex 2, html tooltip</span>
demo
Ex 1, basic tooltipEx 2, html tooltip