What is the easiest, cleanest way to create an HTML mouseover tool tip without using JavaScript?
<img id=Pennstate src="/blah" style="cursor:pointer;">
mouse over that and have a a nice tooltip "We are Pennstate!"
The easiest way is to use the native HTML title
attribute:
<img src="https://stackoverflow.com/favicon.ico"
style="cursor:pointer;"
title="Stack Overflow">
But if you need more, try the tooltip widget provided by jQuery UI since version 1.9.
If you don't care much what the tooltip looks like you can always just use the "title" attribute
You may use a pseudoelement as a tooltip, setting its content from a data property using the css attr()
function.
[data-tooltip]:hover::after {
display: block;
position: absolute;
content: attr(data-tooltip);
border: 1px solid black;
background: #eee;
padding: .25em;
}
<div data-tooltip="We are Pennstate!">Pennstate</div>
The modern approach (≥ 2024) would be to use the Popover API. As it currently doesn't support hover as a trigger, we'd need a sprinkle of JavaScript to make that work. Popovers are usually designed for dialogs/modals, but we can make use of the anchor
rules (more on that here: https://developer.chrome.com/blog/introducing-popover-api#anchor_positioning) to position it atop the trigger button.
const popover = document.querySelectorAll("[popovertarget][data-trigger='hover']");
popover.forEach((e) => {
const target = document.querySelector("#" + e.getAttribute("popovertarget"));
e.addEventListener("mouseover",()=>{
target.showPopover();
});
e.addEventListener("mouseout",()=>{
target.hidePopover();
});
});
body {
height: 10rem;
display: grid;
place-items: center;
}
.tooltip {
bottom: anchor(bottom);
translate: 0 80%;
border-radius: 0.5rem;
}
<button id="tip-anchor" popovertarget="fun-fact" data-trigger="hover">ℹ️</button>
<div popover anchor="tip-anchor" id="fun-fact" class="tooltip">The narwahl tusk develops from a tooth!</div>
This is the easiest... all browsers now seem to have tooltips so they can interpret from the HTML directly:
<span title={timezoneOffset} data-toggle="tooltip">
{timeZoneAbbreviation}
</span>
This is not an official way but it can reduce the burden of writing extra code for tool tip by wrapping your required element inside a abbreviation abbr tag
<abbr title="this is a tool tip">
<div> any content....<div/>
<abbr/>