JSFiddle - React, Tailwind, and code Playground
by ckissi
HTML
<div id="element">Hover over me</div>
<div id="tooltip">This is a tooltip</div>
CSS
#tooltip {
visibility: hidden;
width: 120px;
background-color: #555;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
position: absolute;
z-index: 1;
bottom: 150%;
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
display: block;
height: 30px;
}
JavaScript
const element = document.getElementById("element");
const tooltip = document.getElementById("tooltip");
element.addEventListener("mouseover", (event) => {
// Get the element position
const rect = event.target.getBoundingClientRect();
const { left, top } = rect;
// Update the tooltip position
tooltip.style.left = `${left + window.scrollX}px`;
tooltip.style.top = `${top + window.scrollY}px`;
// Make the tooltip visible
tooltip.style.visibility = "visible";
tooltip.style.opacity = "1";
});
element.addEventListener("mouseout", () => {
// Hide the tooltip
tooltip.style.visibility = "hidden";
tooltip.style.opacity = "0";
});