I’m using Chart.js to display some financial data in a pie chart, along with external tooltips. The data in the tooltip is displayed currently like this:
“Invoiceable: 1,202.5”
What I want is to firstly round the number to 1,200, and then add a ‘£’ sign before the data point so it reads:
“Invoiceable: £1,200”
I’m struggling to work out how to do this in this code below. Can anyone help?
tooltip: {
// Disable the on-canvas tooltip
enabled: false,
external: function(context) {
// Tooltip Element
let tooltipEl = document.getElementById('chartjs-tooltip');
// Create element on first render
if (!tooltipEl) {
tooltipEl = document.createElement('div');
tooltipEl.id = 'chartjs-tooltip';
tooltipEl.innerHTML = '<table></table>';
document.body.appendChild(tooltipEl);
}
// Hide if no tooltip
const tooltipModel = context.tooltip;
if (tooltipModel.opacity === 0) {
tooltipEl.style.opacity = 0;
return;
}
// Set caret Position
tooltipEl.classList.remove('above', 'below', 'no-transform');
if (tooltipModel.yAlign) {
tooltipEl.classList.add(tooltipModel.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Set Text
if (tooltipModel.body) {
const titleLines = tooltipModel.title || [];
const bodyLines = tooltipModel.body.map(getBody);
let innerHtml = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach(function(body, i) {
innerHtml += '<tr><td><div class="tooltip">'+ body + '</div></td></tr>';
});
innerHtml += '</tbody>';
let tableRoot = tooltipEl.querySelector('table');
tableRoot.innerHTML = innerHtml;
}
const position = context.chart.canvas.getBoundingClientRect();
const bodyFont = Chart.helpers.toFont(tooltipModel.options.bodyFont);
// Display, position, and set styles for font
tooltipEl.style.opacity = .8;
tooltipEl.style.position = 'absolute';
tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
tooltipEl.style.font = bodyFont.string;
tooltipEl.style.padding = tooltipModel.padding + 'px ' + tooltipModel.padding + 'px';
tooltipEl.style.pointerEvents = 'none';
}
}
FTR – I copied the above code from chart.js, which made it work, but I don’t presume to understand it for a second!