Search code examples
javascripttooltiptitle

JavaScript, How to show 'current' data in a tooltip without polling?


I have an html element, (lets say for simplicity) a label, and it has a title, so that a tooltip appears when you hover over the label.

I would like the tooltip to show a snapshot of some associated 'current' data. In actuality, the current price of the object that the label points to, but an analogue of this could be any data that potentially changes with time.

In native JavaScript, how can I detect the activation of the tooltip, so that I can re-calc the data before the tooltip is shown?

I know that I could use setInterval() or something to keep the title string current, but it would be more efficient to only re-calculate the title string when the tooltip is shown.


Solution

  • Something like this may work, but you'll be at the mercy of the latency of the request for updating the data (assuming that the source of the updated price data is a http request or socket connection) and that probably won't be quicker than the browser will display the tooltip. It's certainly not going to be consistent or reliable.

    <p id="text" title="initialtitle">Text</p>
    <script>
        var n = 0;
    
        document.getElementById("text");
            text.onmouseover = function() {
                n++;
                text.title = n;
        };
    </script>
    

    Depending on the specifics of what you're doing and how much room for maneuver you have, another solution could be to open a WebSocket to a server which then updates all clients with the updated price information when it changes. That way the data is sent to the cleint as fast as possible without constant http polling, and timers aren't necessary.

    Of course, if the source of the data is a calculation within the JavaScript itself without having to get information from a server, then a mere modification of the above for your needs could suit.

    Here's a jsfiddle to play around with.