Is it possible to load text file to bootstrap tooltip title?

Viewed 182

I want to load an text file to my bootstrap tooltip title.

This is a part of my code working with simple values:

<div>
    <a id="A" type="button" class="btn btn-outline-secondary btn-lg" data-toggle="tooltip" dataplacement="bottom" href="Some action"> A</a>
    <a id="B" type="button" class="btn btn-outline-secondary btn-lg" data-toggle="tooltip" dataplacement="bottom" href="Some action"> B</a>
    <a id="C" type="button" class="btn btn-outline-secondary btn-lg" data-toggle="tooltip" dataplacement="bottom" href="Some action"> C</a>
</div>

<script>
    $(function () {
        $('[data-toggle="tooltip"]').tooltip()
    });

    $('#A').tooltip({
        title: "June"
    });
    $('#B').tooltip({
        title: "July"
    });
    $('#C').tooltip({
        title: "August"
    });
</script>

I have a text file with:

June
July
August

This text file will be updated with some script and i'm trying to "dynamicaly" put those 3 values on my 3 tooltips titles.

I tried a few things with XMLHttpRequest() or $.get() but i'm not having the right result.

For example i tried:

function(Atooltip(node) {
    $.get("My text File", function(responseText) {
        var Month = responseText;
    });
    console.log(Month);
    return Month;
}

$('#A').tooltip({
    title: Atooltip
});

The console log returns:

June
July
August

But my tooltip title is empty.

Is there a better way to do it ?

Or perhaps a way to make a loop doing the tree lines of the file in a row ?

1 Answers

ajax is asynchronous, with your code you are injecting the value before the call has actually returned it, so it is empty. Try with

 $.get("My text File", function (responseText) {
        var Month = responseText;
        console.log(Month);
    }).done(function (Month) {
        console.log(Month);
        $('#A').tooltip({
            title: Month
        });
    });

To split the results, given the file structure you posted (one month per line) you can:

$.get("My text File", function (responseText) {
    let Months = responseText.split("\n");
    // Months is now an array -> ["June", "July", "August"]
}).done(function (Month) {
    console.log(Month);

    $('#A').tooltip({
        title: Month[0] // June
    });
    
    $('#B').tooltip({
        title: Month[1] // July
    });

    // Keep going as much as you need ...
});

In the future consider to retrieve json insteaed of plain text so that it'll be easier to assign multiple values.

Related