Reputation: 4375
So, let's say I have this span with a title
attribute:
<span title="Tooltip" id="mySpan">Span</span>
This shows the tooltip just fine, but I'd like to attach some kind of event listener for when the title shows with either JavaScript or JQuery. e.g. something like (obviously "title"
isn't a valid event):
document.getElementById("mySpan").addEventListener("title", function () {
console.log("Tooltip shown");
});
I know that I could create my own tooltip with JavaScript and a mouseover
event like this:
document.getElementById("mySpan").addEventListener("mouseover", function (event) {
console.log("Tooltip shown");
document.getElementById("myTooltip").style.display = 'block';
document.getElementById("myTooltip").style.top = (event.clientY + 5) + 'px';
document.getElementById("myTooltip").style.left = (event.clientX + 5) + 'px';
});
document.getElementById("mySpan").addEventListener("mouseout", function () {
document.getElementById("myTooltip").style.display = 'none';
});
#myTooltip {
position: absolute;
background-color: lightgray;
padding: 2px 4px;
font-size: 10px;
}
<span id="mySpan">Span</span>
<span id="myTooltip" style="display: none;">Tooltip</span>
But this means I have to recreate the style of the title
attribute from scratch, which changes from browser to browser, and from OS to OS, and I'd really rather not change the standard tooltip that the user is used to seeing.
So, in summary, is it possible to attach some sort of event listener for when the title
attribute displays?
Upvotes: 1
Views: 4638
Reputation: 4375
Disclaimer: this isn't actually an event listener.
It's not the greatest of solutions, but it works. All it does is start a setTimeout
for 0.5s (that was based on trial and error, couldn't find it in any docs) on mouseover
, and cancel it when you mouseout
. It works for me, but it might not work if the delay changes based on the browser / OS.
var titleShowTimeout;
document.getElementById("mySpan").addEventListener("mouseover", function (event) {
titleShowTimeout = setTimeout(function () {
console.log("Tooltip shown");
}, 500);
});
document.getElementById("mySpan").addEventListener("mouseout", function () {
clearTimeout(titleShowTimeout);
});
<span title="Tooltip" id="mySpan">Span</span>
Upvotes: 2
Reputation: 727
You can use jQuery-ui Tooltip Widget
$( document ).tooltip();
$("#inputhelp").tooltip({
open: function( event, ui ) {
console.log('Text tooltip');
}
});
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>
<a href="#" title="Anchor description">Anchor text</a>
<input id="inputhelp" title="Input help">
</p>
Upvotes: 1