Consider this innovative approach that combines elements from both mshameer
's answer and the provided bin.
For a practical demonstration, check out this Solution JSBin
This script offers two ways to create a tooltip. The first method involves declaring it in an HTML attribute using the '|' character as a line delimiter. The second method allows for directly passing the element and its tooltip as a JQuery object. This means you can fulfill your HTML-declaration desires without compromising on click styling requirements.
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 function createDataOver
handles all the heavy lifting:
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) {
// 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 initially
$el.append($holder);
// Implement a closure with a timeout variable
// To prevent immediate disappearance
(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 parent of the tooltip to have position: relative
. It does not have the same behavior as the title
attribute regarding entry bounds – a display: block
h3
element will react to mouseenter
across its entire width. Given that the provided JSBin uses a table, this discrepancy may not be significant.
An effort has been made to manage timing issues by incorporating a half-second timeout on mouse leave. This enables users to hover back over the element within that timeframe to retain visibility rather than losing it immediately.