32

There is a new Tooltip Widget in jQuery UI 1.9, whose API docs hint that AJAX content can be displayed in it, but without any further details. I guess I can accomplish something like that with a synchronous and blocking request, but this isn't what I want.

How do I make it display any content that was retrieved with an asynchronous AJAX request?

4 Answers 4

64

Here is a ajax example of jqueryui tootip widget from my blog.hope it helps.

$(document).tooltip({
    items:'.tooltip',
    tooltipClass:'preview-tip',
    position: { my: "left+15 top", at: "right center" },
    content:function(callback) {
        $.get('preview.php', {
            id:id
        }, function(data) {
            callback(data); //**call the callback function to return the value**
        });
    },
});
1
  • It works but I dont understand why doing a callback(data) would return the data here? It is very confusing since to me, it look like the callback, as an argument, suddenly make a function call..
    – Loredra L
    Jan 24, 2019 at 14:36
19
+50

This isn't a complete solution obviously, but it shows the basic technique of getting data dynamically during the open event:

$('#tippy').tooltip({
    content: '... waiting on ajax ...',
    open: function(evt, ui) {
        var elem = $(this);
        $.ajax('/echo/html').always(function() {
            elem.tooltip('option', 'content', 'Ajax call complete');
         });
    }
});

See the Fiddle

3
  • 1
    I have noticed that on the fiddle, if you pass your mouse over the tooltiped text quickly, that the tooltip can get suck in the "off" mode. I don't know if this is a bug in tooltip, interaction with the ajax code, or just a version incompatibility between jquery-ui 1.9 and jsFiddle's jQuery 1.8.x. Nov 5, 2012 at 3:33
  • There's actually a few interesting things you can do with this, but I would have to know more about your specific use case to offer any more detailed suggestions. Nov 5, 2012 at 3:41
  • y, u can do great stuff with this, i am using hidden divs for tooltips and in open fucntion i do ajax call only if the particular hidden div is empty.
    – sanjuro
    Jan 5, 2014 at 17:01
3

One thing to lookout for when using the tooltip "content" option to "AJAX" the text into the tooltip, is that the text retrieval introduces a delay into the tooltip initialization.

In the event that the mouse moves quickly across the tooltip-ed dom node, the mouse-out event may occur before the initialization has completed, in which case the tooltip isn't yet listening for the event.

The result is that the tooltip is displayed and does not close until the mouse is moved back over the node and out again.

Whilst it incurs some network overhead that may not be required, consider retrieving tooltip text prior to configuring the tooltip.

In my application, I use my own jquery extensions to make the AJAX call, parse the resutls and initialise ALL tooltips, obviously you can use jquery and/or your own extensions but the gist of it is:

Use image tags as tooltip anchors, the text to be retrieved is identified by the name atrribute:

<img class="tooltipclassname" name="tooltipIdentifier" />

Use invoke extension method to configure all tooltips:

$(".tooltipclassname").extension("tooltip");

Inside the extension's tooltip method:

    var ids = "";
    var nodes = this;

    // Collect all tooltip identifiers into a comma separated string
    this.each(function() {
        ids = ids + $(this).attr("name") + ",";
    });

    // Use extension method to call server
    $().extension("invoke", 
    {
        // Model and method identify a server class/method to retrieve the tip texts
        "model": "ToolTips", 
        "method": "Get",

        // Send tooltipIds parameter 
        "parms":  [ new myParmClass("tipIds", ids ) ],

        // Function to call on success. data is a JSON object that my extension builds
        // from the server's response
        "successFn": function(msg, data) {

            $(nodes).each(function(){

                // Configure each tooltip:
                // - set image source
                // - set image title (getstring is my extension method to pull a string from the JSON object, remember that the image's name attribute identifies the text)
                // - initialise the tooltip
                $(this).attr("src", "images/tooltip.png")
                    .prop("title", $(data).extension("getstring", $(this).attr("name"))) 
                    .tooltip();
            });
        },
        "errorFn": function(msg, data) { 
            // Do stuff
        }
    }); 

    // Return the jquery object
    return this;
3

Here is an example that uses the jsfiddle "/echo/html/" AJAX call with a jQuery UI tooltip.

HTML:

<body>
<input id="tooltip" title="tooltip here" value="place mouse here">
</body>

JavaScript:

// (1) Define HTML string to be echo'ed by dummy AJAX API
var html_data = "<b>I am a tooltip</b>";

// (2) Attach tooltip functionality to element with id == tooltip
// (3) Bind results of AJAX call to the tooltip
// (4) Specify items: "*" because only the element with id == tooltip will be matched
$( "#tooltip" ).tooltip({
    content: function( response ) {
        $.ajax({ 
        url: "/echo/html/",
        data: {
                'html': html_data
            },
        type: "POST"
        })
          .then(function( data ) {
             response( data );
          });
    },
    items: "*"
});

here is this example on jsfiddle:

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.