Chartjs-How to modify chartjs tooltip to add customized attribute

1👍

Different Labels in Tooltip vs Scale

Just use the tooltipTemplate option

Preview

enter image description here


Script

function Label(short, long) {
  this.short = short;
  this.long = long
}
Label.prototype.toString = function() {
  return this.short;
}

var data = {
    labels: [ 
      new Label("J", "JAN"), 
      new Label("F", "FEB"), 
      new Label("M", "MAR"),
      new Label("A", "APR"),
      new Label("M", "MAY"),
      new Label("J", "JUN"),
      new Label("J", "JUL")
    ],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        }
    ]
};

// create chart
var ctx = document.getElementById("chart").getContext('2d');
new Chart(ctx).Bar(data, {
  tooltipTemplate: "<%if (label){%><%=label.long%>: <%}%><%= value %>",
});


Fiddle – https://jsfiddle.net/7z1s1feg/

0👍

This part of the documentation explain you how to extend the tooltips elements.

var myPieChart = new Chart(ctx).Pie(data, {
    customTooltips: function(tooltip) {

    };
});

Plus, this example show you how to modify the HTML of the tooltip inside this function. The example from GitHub :

var innerHtml = '';
    for (var i = tooltip.labels.length - 1; i >= 0; i--) {
        innerHtml += [
            '<div class="chartjs-tooltip-section">',
            '   <span class="chartjs-tooltip-key" style="background-color:' + tooltip.legendColors[i].fill + '"></span>',
            '   <span class="chartjs-tooltip-value">' + tooltip.labels[i] + '</span>',
            '</div>'
        ].join('');
    }
    tooltipEl.html(innerHtml);

With these elements, you will be able to customize your tooltips however you want.

Leave a comment