JSFiddle - React, Tailwind, and code Playground
by godfrzero
HTML
<!-- Core: Always visible, show optional/additional information -->
<!-- Optional: Triggered in other ways -->
<div class="container">
<span data-tooltip="Woof π">Some content</span>
<div>Some other content</div>
<div>More content!</div>
<button data-tooltip="Meow π">Button</button>
<button>Button</button>
<button>Button</button>
<br>
<span data-tooltip="Rawr π">Some content</span>
<div>Some other content</div>
<div>More content!</div>
</div>
CSS
.myTooltip {
display: none;
border: solid thin black;
background: cyan;
position: absolute;
padding: 6px;
}
.myTooltip:before {
content: ' ';
position: absolute;
top: -20px;
left: calc(50% - 10px);
border: solid 10px transparent;
border-bottom-color: black;
}
JavaScript
function init () {
let $tooltipContainer = document.createElement('div'),
$text = document.createTextNode('Welcome to JS ^_^'),
$container = document.getElementsByClassName('container')[0];
$tooltipContainer.appendChild($text);
$tooltipContainer.setAttribute('class', 'myTooltip');
document.body.insertBefore($tooltipContainer, $container);
document.addEventListener('mouseover', showTooltip);
}
init();
function showTooltip (e) {
let $tooltipContainer = document.getElementsByClassName('myTooltip')[0],
$parent = e.target,
tipContent = $parent.getAttribute('data-tooltip');
getTooltipPosition($parent);
if (tipContent) {
$tooltipContainer.innerText = tipContent;
$tooltipContainer.style.display = 'block';
}
else {
$tooltipContainer.style.display = 'none';
}
}
function getTooltipPosition ($el) {
let clientRect = $el.getBoundingClientRect();
}