[Chartjs]-Chart.js โ€“ custom tooltip with multiple values

6๐Ÿ‘

โœ…

I am not 100% sure of the desired output but this is my take.

In short, when you define your own customTooltips you are overriding the default tooltipTemplate stated in the options.

So, removing the customTooltips and defining an output format for the template yields the (I think) desired results.

To accomplish the output neatly, however, I added a new object called DataPoint and defined as this:

function DataPoint(id, age, milepost) {
    this.id = id;
    this.age = age;
    this.milepost = milepost;
    this.tooltip = "Bridge ID:" + id + ", Bridge Age: " + age +", Milepost: " + milepost;
}

DataPoint.prototype.toString = function () {
        return this.id;
};

This allows me to contain all the necessary data bits into one object (and then I only manipulate an array of those instead of multiple arrays)

Then, you set up your array of objects as your Labels for the table

 var barChartData2 = {
        labels: bridgeDataPoints, /* this is the array of DataPoints */
        datasets: [{
            fillColor: ["rgba(220,220,220,0.5)"],
            strokeColor: "rgba(151,187,205,1)",
            pointColor: "rgba(151,187,205,1)",
            pointStrokeColor: "#fff",
            data: bridge_age_grab,
        }]
    };

Finally, the tooltipTemplate was defined as follows:

OLD Version (prior to v3)

tooltipTemplate: "<%if (label){%><%=label.tooltip%><%}%>",

UPDATE: NEW for ChartJS v3

put it inside options object.

options: {
          tooltips: {
            callbacks: {
              label: function(tooltipItem, data) {
                  // console.log(tooltipItem);
                  // return 'id: ' + tooltipItem.xLabel.id+' | '+' age: '+tooltipItem.xLabel.age;
                },
                title: function(tooltipItem, data) {
                    // return 'Date: ' + tooltipItem[0].xLabel.date;
                    return 'id: ' + tooltipItem[0].xLabel.id+'\nage: ' + tooltipItem[0].xLabel.age;
                }
            }
          }
// try out your combinations
}

which means, if a label exists for each element, display the tooltip property for it. Since we defined the tooltip property for our DataPoint elements as
this.tooltip = "Bridge ID:" + id + ", Bridge Age: " + age +", Milepost: " + milepost; the desired output is obtained.

Let me know if this helps.

See the updated fiddle here

Leave a comment