Wessi
Wessi

Reputation: 1822

customizing tooltip on chart.js bar chart

I would like to customize the tooltip on a chart.js bar chart. This is my code:

$(function () {
  var barData = no_houses_person

var barOptions = {
    scaleBeginAtZero: true,
    scaleShowGridLines: true,
    scaleGridLineColor: "rgba(0,0,0,.05)",
    legend: {
        display: true,
        position: 'top'
    },
    scaleGridLineWidth: 1,
    barShowStroke: true,
    barStrokeWidth: 1,
    barValueSpacing: 5,
    barDatasetSpacing: 1,
    responsive: true,
};
   var ctx = document.getElementById("barChart").getContext("2d");
   var myNewChart = new Chart(ctx, {
    type: 'bar',
    data: barData,
    options: barOptions
});
});

I have tried adding tooltipTemplate: "<%if (label){%><%=label%> <%}%>(<%= value %> example)", to barOptions but it has no effect.

Upvotes: 1

Views: 16466

Answers (1)

Keno
Keno

Reputation: 3955

Chart.js moved from Templates to Object interfaces in v2+, so for instance If you just want to modify the tooltip text...

tooltips: {
    callbacks: {
        label: function(tooltipItem) {
            return "$" + Number(tooltipItem.yLabel) + " and so worth it !";
        }
    }
}

Result:

enter image description here

Codepen: Chart.js Custom Tooltip

For more complex tooltip customizations see their samples on github: tooltips

Upvotes: 12

Related Questions