Chartjs-How to set a global chart.js tooltip label callback

1👍

There are 2 ways, the first one is by checking if the value is a number, this way you can get the xAxes value if its a horizontal bar. Fallback in else for if both axis are text values

Chart.defaults.global.tooltips.callbacks.label = function(tooltipItem, data, index) {
    var label = data.datasets[tooltipItem.datasetIndex].label || '';
    if (label) {
        label += ': ';
    }
    if (typeof tooltipItem.yLabel === 'number') {
        label += tooltipItem.yLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    } else if (typeof tooltipItem.xLabel === 'number') {
        label += tooltipItem.xLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    } else {
        label += tooltipItem.value
    }
    return label;
}

You can also check if the value from the tooltip is a number and use that instead of the labels, this will require a typecast so it will be more resource intensive:

Chart.defaults.global.tooltips.callbacks.label = function(tooltipItem, data, index) {
    var label = data.datasets[tooltipItem.datasetIndex].label || '';
    if (label) {
        label += ': ';
    }
    if (Number(tooltipItem.value)) {
        label += Number(tooltipItem.value).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    } else {
        label += tooltipItem.value
    }
    return label;
}

Leave a comment