Question

I have some words wrapped inside span element with class "tooltipX", where "X" is a number. The number grows with an array "Data" which holds description for the tooltip. How can I show the description for the right element? I hope for something like the code below, but I don't know how to loop it.

$( document ).tooltip({
items: ".tooltip"+X+"",
content: Data[X].desc
});

JSFiddle

Was it helpful?

Solution

Instead of using specific classes, you could broaden the class and select them all. In addition, use a data-* attribute to store the index of the Data to use for the tooltip. So, change your HTML to follow this:

<span class="tooltip" data-tooltip-index="0">

(obviously changing the data-tooltip-index value per span)

Also, instead of passing a string to content, you can pass a function, and have it dynamically return the specific item from Data that you want. This function will execute every time the tooltip needs to be shown and uses the returned value as its contents. In this function, you would get the element's data-tooltip-index value (using this), and get the corresponding array value from Data. So, change your JavaScript to this:

$(document).tooltip({
    items: ".tooltip",
    content: function () {
        var index = $(this).attr("data-tooltip-index");
        return Data[index].desc;
    }
});

DEMO


References:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top