Here's a solution that combines some aspects of mshameer
answer with the bin you provided.
JSBin Solution
This script has two methods for creating a tooltip. The first can be declared in the HTML attribute with the symbol |
serving as a line separator, and the second allows you to directly pass an element and its tooltip as a jQuery object. This means that if you don’t need any particular style of styles, you don’t need to leave dreams in the description of the HTML declaration.
HTML:
<h1 data-over="You have hovered|Over this">Here is a title</h1> <p id="test">TEST</p>
JavaScript to search for the data-over
attribute:
// Search for text if it 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);
createDataOver
does the real job:
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); }); }()); }
Warnings
This solution requires the parent hint to be position: relative
. It will also not have the same input borders as the title
attribute - the display: block
h3
element will respond to the mouseenter
along its entire line. Since your provided JSBin uses a table, this may not be a problem.
I also tried to control the time using a half-second timeout on the mouse web, so the user can go back to the item during this time to continue browsing, and not immediately lose sight of it.