Search code examples
javascriptjqueryjquery-pluginstooltip

How to separate out the tooltip text from the HTML file


I am using this plugin for tooltip. It uses title attribute as tooltip text placeholder. There are too many tooltip text, I would like to put them all in a place in order to maintain or update easily. What could be a good approach?

My idea is to create a map in js file, eg:

var tooltiptext =
[{
"label_1": "description for label 1",
"label_2": "description for label 2",
"label_3": "description for label 3",
...
}]

And use jquery to add these title content into the page in $(document).ready. Is this a good idea?


Solution

  • You don't event need the square braces. Let's assume that the label in the object represents the ID of the element. Then use:

    var tooltiptext = {
        "label_1": "description for label 1",
        "label_2": "description for label 2",
        "label_3": "description for label 3",
        //....
        "label_n": "description for label n"
    };
    $.each(tooltiptext, function(label, title){
        $("#" + label).attr("title", title).tooltip();
    });
    

    Inside the loop, you're setting the title attribute of the element. Then, tooltip is invoked.