Add a tooltip to a div
For the basic tooltip, you want:
<div title="This is my tooltip">
like:
.visible { height: 3em; width: 10em; background: yellow;}
<div title="This is my tooltip" class="visible"></div>
For a fancier javascript version, you can look into:
https://jqueryhouse.com/best-jquery-tooltip-plugins/
The above link gives you 25 options for tooltips.
It can be done with CSS only, no javascript at all : running demo
Apply a custom HTML attribute, eg.
data-tooltip="bla bla"
to your object (div or whatever):<div data-tooltip="bla bla"> something here</div>
Define the
:before
pseudoelement of each[data-tooltip]
object to be transparent, absolutely positioned and withdata-tooltip=""
value as content:[data-tooltip]:before { position : absolute; content : attr(data-tooltip); opacity : 0;}
Define
:hover:before
hovering state of each[data-tooltip]
to make it visible:[data-tooltip]:hover:before { opacity : 1;}
Apply your styles (color, size, position etc) to the tooltip object; end of the story.
In the demo I've defined another rule to specify if the tooltip must disappear when hovering over it but outside of the parent, with another custom attribute, data-tooltip-persistent
, and a simple rule:
[data-tooltip]:not([data-tooltip-persistent]):before { pointer-events: none;}
Note 1: The browser coverage for this is very wide, but consider using a javascript fallback (if needed) for old IE.
Note 2: an enhancement might be adding a bit of javascript to calculate the mouse position and add it to the pseudo elements, by changing a class applied to it.
You don't need JavaScript for this at all; just set the title
attribute:
<div title="Hello, World!"> <label>Name</label> <input type="text"/></div>
Note that the visual presentation of the tooltip is browser/OS dependent, so it might fade in and it might not. However, this is the semantic way to do tooltips, and it will work correctly with accessibility software like screen readers.
Demo in Stack Snippets
<div title="Hello, World!"> <label>Name</label> <input type="text"/></div>