Here's a solution that combines some of the aspects of mshameer
's answer with your provided bin.
Solution JSBin
This script has two methods of creating a tooltip. The first can be declared in an HTML attribute with the |
character serving as a line delimiter, and the second allows directly passing the element and its tooltip as a JQuery object. This means that if you don't need any specific click styling, you don't have to leave your HTML-declaration dreams behind.
HTML:
<h1 data-over="You have hovered|Over this">Here is a title</h1>
<p id="test">TEST</p>
JavaScript for searching by the data-over
attribute:
// Search for text if it's simple in the HTML
var $dataElements = $("[data-over]");
$dataElements.each(function (index, el) {
var $el = $(el);
var text = $el.attr("data-over");
if (text) {
// Split by "|"
text = text.split("|");
createDataOver($el, text);
}
});
JavaScript for manually adding a tooltip:
// Or provide it yourself.
var $testData = $(document.createElement("span"));
$testData.text("Click me.").click(function () {
alert("Clicked");
});
createDataOver($("#test"), $testData);
The createDataOver
does the real work:
function createDataOver($el, data) {
var $holder = $(document.createElement("div"));
$holder.addClass("over hidden");
// Check if we provided JQuery or a string array
if (data instanceof jQuery) {
// Manually make it relatively positioned
$el.css("position", "relative");
data.addClass("over-line");
$holder.append(data);
}
else {
data.forEach(function (line) {
var $line = $(document.createElement("span"));
$line.text(line);
$line.addClass("over-line");
$holder.append($line);
});
}
// append with the hidden class to start
$el.append($holder);
// Create a closure with a timeout variable
// So it doesn't disappear immediately if
// we don't want it to!
(function closure() {
var timeoutCancel = -1;
$el.mouseenter(function () {
if (timeoutCancel !== -1) {
clearTimeout(timeoutCancel);
timeoutCancel = -1;
}
$holder.removeClass("hidden");
});
$el.mouseleave(function () {
timeoutCancel = setTimeout(function () {
if (timeoutCancel !== -1)
$holder.addClass("hidden");
}, 500);
});
}());
}
Caveats
This solution requires the tooltip parent to be position: relative
. It also won't have the same entry bounds as the title
attribute - a display: block
h3
element will respond to the mouseenter
across its full row. Since your provided JSBin uses a table, this may not be an issue.
I also tried to control for the timing by having a half-second timeout on the mouseleave, that way the user can mouse back over the element in that time to keep viewing it rather than losing view of it immediately.