JSFiddle - React, Tailwind, and code Playground
by leopoldthecuber
HTML
<div>
<p>Test Paragraph</p>
</div>
CSS
html, body {
height: 100%;
margin: 0;
padding: 0;
}
div {
padding: 50px;
}
p {
display: inline-block;
}
.tooltip {
width: 200px;
position: absolute;
background: black;
color: white;
transform: translateY(-100%);
}
JavaScript
class Tooltip {
constructor(targetEl, title) {
this.targetEl = targetEl;
this.el = document.createElement('span');
this.el.innerText = title;
this.el.classList.add('tooltip');
this.el.style.display = 'none';
document.body.appendChild(this.el);
this.show = this.show.bind(this);
this.hide = this.hide.bind(this);
this.targetEl.addEventListener('mouseenter', this.show);
this.targetEl.addEventListener('mouseleave', this.hide);
}
show() {
const { top, left, width } = this.targetEl.getBoundingClientRect();
this.el.style.display = 'block';
this.el.style.top = `${top - 5}px`;
this.el.style.left = `${left + width / 2 - 100}px`;
}
hide() {
this.el.style.display = 'none';
}
}
const tooltip = new Tooltip(document.querySelector('p'), 'Tooltip text');