Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Add a tooltip to a div

I have a div tag like this:

<div>
<label>Name</label>
<input type="text"/>
</div>
*
How can I display a tooltip on :hover of the div, preferably with a fade in/out effect.
by

3 Answers

aashaykumar
You can toggle a child div during onmouseover and onmouseout like this:

function Tooltip(el, text) {
el.onmouseover = function() {
el.innerHTML += '<div class="tooltip">' + text + '</div>'
}
el.onmouseout = function() {
el.removeChild(el.querySelector(".tooltip"))
}
}

//Sample Usage
Tooltip(document.getElementById("mydiv"),"hello im a tip div")
sandhya6gczb
It can be done using only CSS. No JavaScript required.
Apply the custom HTML attribute.
for example

<div data-tooltip="bla bla">
something here
</div>

Define the :before pseudoelement of each [data-tooltip] object to be transparent, absolutely positioned and with data-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;
}
RoliMishra
HTML
<td>
<%# (Eval("Name").ToString().Length > 65) ? Eval("Name").ToString().Substring(0, 60) + "..." : Eval("Name")%>
<span class="showonhover">
<a href="#"><%# (Eval("Name").ToString().Length > 65) ? "More" : "" %></a>
<span class="hovertext">
<%# Eval("Name") %>
</span>
</span>
</td>


CSS

.showonhover .hovertext { display: none;}
.showonhover:hover .hovertext {display: inline;}
a.viewdescription {color:#999;}
a.viewdescription:hover {background-color:#999; color: White;}
.hovertext {position:absolute;z-index:1000;border:1px solid #ffd971;background-color:#fffdce;padding:11px;width:150px;font-size: 0.75em;}

Login / Signup to Answer the Question.