JSFiddle - React, Tailwind, and code Playground
by Paco86
HTML
<a
href="#"
class="tooltip">
tooltip
<span role="tooltip" >
this is a tooltip
</span>
</a>
just add the tool class and the
<a
href="#"
class="tooltip">
tooltip 2
<span role="tooltip">
this is a tooltip 2
</span>
</a>
attribute with your tooltip message.
CSS
.tooltip {
position: relative;
}
[role="tooltip"] {
position: absolute;
display: none;
border: 1px solid #000;
padding: 10px;
background-color: #efefef;
top: 20px;
left: 0;
width: 200px;
}
JavaScript
document.querySelectorAll('.tooltip').forEach((el) => {
['mouseenter', 'focus'].forEach((userEvent) => {
el.addEventListener(userEvent, (event) => {
var contentEl = event.target.querySelector('[role="tooltip"]');
contentEl.style.display = 'block';
var contentElPosition = contentEl.getBoundingClientRect();
if (contentElPosition.right > window.innerWidth) {
contentEl.style.left = (window.innerWidth - contentElPosition.right) - 40 + 'px'
}
if (contentElPosition.bottom > window.innerHeight) {
contentEl.style.top = (window.innerHeight - contentElPosition.top) - 40 + 'px'
}
});
});
['mouseleave', 'blur'].forEach((userEvent) => {
el.addEventListener(userEvent, (event) => {
var contentEl = event.target.querySelector('[role="tooltip"]');
contentEl.style.display = 'none';
contentEl.style.left = 0;
});
});
});