Search code examples
jqueryajaxtooltiptooltipster

Generate a tooltip in Tooltipster based on the contents of the element


I'm using a Tooltipster library to generate tooltip and used their simple AJAX-custom-function example as a basis. I need to modify that though so instead of querying a static "http://example.com/ajax.php" as seen in their example it would instead get "http://example.com/ajax.php?id=contents_of_the_element_being_clicked". So for example, if I have a <span>textbook</span> in my HTML, the contents link for the popup would be "http://example.com/ajax.php?id=textbook".

I've successfully repurposed the example to activate on every <span>, what I cannot do is understand how to bring the innerHTML contents of that <span>.

So all I'm looking for is that one line that populates a variable with the element's contents which I can later append to a $.get ... function(data) request.


Solution

  • You can use use the html() function from jquery to extract the inner html. Furthermore, you can use param() to encode the extracted html.

    var param = "?" + $.param({ id: origin.html() });       
    

    Full example (working with Tooltipster 3.3.0 and jQuery 1.10):

    $('.tooltip').tooltipster({    
        functionBefore: function(origin, continueTooltip) {
            var param = "?" + $.param({ id: origin.html() });       
            if (origin.data('loaded') !== true) {
                $.get('example.com/ajax.php' + param, function(data) {
                    origin.data('loaded', true);
                    origin.tooltipster('content', data.id);
                    continueTooltip();
                });            
            }
            else {
                continueTooltip();        
            }
        }
    });
    

    Tooltipster Version 4:

    $('.tooltip').tooltipster({    
        content: 'Loading...',
        functionBefore: function(instance, helper) {
            var $origin = $(helper.origin);
            var param = "?" + $.param({ id: $origin.html() });       
            if ($origin.data('loaded') !== true) {
                $.get('example.com/ajax.php' + param, function(data) {
                    instance.content(data.id);
                    $origin.data('loaded', true);
                });            
            }
        }
    });
    

    HTML:

    <span class="tooltip" title="This is my span's tooltip message!">Some text test</span>