Search code examples
javascriptjqueryhtmltooltipevent-listener

Is there an event for when the title attribute shows the tooltip?


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?


Solution

  • 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>