Search code examples
javascriptvariablesattributestooltipster

Attributes / vars in tooltipster are ignored


I've been trying for two days to figure out why tooltipster (which is great btw) is not taking into account any var declared in the javascript / head section. For instance:

<script>
$(document).ready(function() {
    $('.tooltip').tooltipster({
        var data = 'toto';
        contentAsHTML: true,
        animation: 'slide',
        delay: 100,
        content : $(data)
        });
});
</script>

with:

<img src="Pics/winter.png" alt="winter" border="1" class="tooltip" />

is not working at all (meaning the tooltip is not showing up in the HTML page). I tried several coding variations, including adding ' ; ' etc. but it doesn't change the result. I also tried to get an element's attribute using:

content : '$(this).attr('alt')'

which is my final goal, and it doesn't work either. What am I missing?


Solution

  • I've made a quick jsFiddle to demo the "correct" way of setting the content of the tooltip from the originating element - on it's intialization.

    The reason this wasn't working before was due to:

    1. You declaring the variable data within the JSON object passed to the tooltipster function - this is invalid syntax for JavaScript.
    2. Your second attempt was closer, but using this in the content property is an ambiguous reference to an "outside" this scope - likely unrelated to the tooltipster instance or HTML node you were after.

    Here's the amended code that should do what you want:

    $(document).ready(function() {
        $('.tooltip').tooltipster({
            contentAsHTML: true,
            animation: 'slide',
            delay: 100,
            functionInit: function(instance, helper) {
              var alt = $(helper.origin).attr('alt');
              instance.content(alt);
            }
        });
    });
    

    I hope this helps :)