score:1
Good, although with the previous solution to solve the problem I think that the solution offered by chart.js is a bit ... Confusing. The same can be applied in a more understandable way. Based on the chart.js guide I have created an HTML that will be used in the tooltip. What I got was the following:
First I give you the code used and then I explain it:
tooltip: {
// Disable the on-canvas tooltip
enabled: false,
external: (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 (above, below,no-transform ).As I need above I don't delete that class
tooltipEl.classList.remove('below', 'no-transform');
// Set HTML & Data
if (tooltipModel.body) {
const dataFromCurrentElement = tooltipModel.dataPoints[0];
const currentElement = dataFromCurrentElement.dataIndex;
const formattedValue = dataFromCurrentElement.formattedValue.trim();
const currentDataToShow = formattedValue.substr(1, formattedValue.length - 2).split(' ');
const innerHtml = `
<div style="border-collapse: separate; overflow: hidden; border-radius: 10px; box-shadow: 0 6px 12px rgba(0,0,0,.175);">
<div style="background-color: #ECEFF1; padding-top: 5px; padding-bottom: 6px; padding-left: 7px; color: #000; font-family: 'Poppins'; font-size: 14px; border-bottom: solid 1px #DDD">
Name
</div>
<div style="display: flex; padding: 1.2rem; background-color: white">
<div style="display: flex; margin-right: 1.2rem;align-items: center; ">
<div style="border-radius: 100%; background-color: #6785C1; height: 13px; width: 13px;"></div>
</div>
<div style="display: flex; flex-direction: column; font-family: 'Poppins'; font-size: 14px">
<div>Revenue: <span style="font-weight: 600">${currentDataToShow[0].substr(0, currentDataToShow[0].length - 1)}</span></div>
<div>Revenue per employee: <span style="font-weight: 600">${currentDataToShow[1].substr(0, currentDataToShow[1].length - 1)}</span></div>
<div>Net income per employee: <span style="font-weight: 600">${this.customReportUtilities.parseNumberFunction(Number(currentDataToShow[2]) * 100)}</span></div>
</div>
</div>
</div>
`;
tooltipEl.querySelector('table').innerHTML = innerHtml;
}
const position = context.chart.canvas.getBoundingClientRect();
// Display, position, and set styles for font
tooltipEl.style.opacity = '1';
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.padding = tooltipModel.padding + 'px ' + tooltipModel.padding + 'px';
tooltipEl.style.pointerEvents = 'none';
}
}
This is the same code, it is not necessary to duplicate it, with the above it is worth
We hide the tooltip from chartjs using tooltip false, then in external we pass the function to use our HTML as tooltip
let tooltipEl = document.getElementById('chartjs-tooltip');
We collect the container with id chartjs-tooltip, if it does not exist (the mouse had not been placed on the graph) we create it (it is the following if).
let tooltipEl = document.getElementById('chartjs-tooltip'); if (!tooltipEl) { tooltipEl = document.createElement('div'); tooltipEl.id = 'chartjs-tooltip'; tooltipEl.innerHTML = '<table></table>'; document.body.appendChild(tooltipEl); }
We hide the tooltip when the user does not have the cursor over an element (this is because otherwise it would always be seen.
const tooltipModel = context.tooltip; if (tooltipModel.opacity === 0) { tooltipEl.style.opacity = '0'; return; }
We indicate the position of the tooltip, to choose between above, below or no-transform. I have removed all but above because it is the class I want to keep.
tooltipEl.classList.remove('below', 'no-transform');
We get the data for the current element and form the HTML with its styles ... Saving it in a variable as a string and we pass it our string with the HTML.
if (tooltipModel.body) { const dataFromCurrentElement = tooltipModel.dataPoints[0]; const currentElement = dataFromCurrentElement.dataIndex; const formattedValue = dataFromCurrentElement.formattedValue.trim(); const currentDataToShow = formattedValue.substr(1, formattedValue.length - 2).split(' '); const innerHtml = ` <div style="border-collapse: separate; overflow: hidden; border-radius: 10px; box-shadow: 0 6px 12px rgba(0,0,0,.175);"> <div style="background-color: #ECEFF1; padding-top: 5px; padding-bottom: 6px; padding-left: 7px; color: #000; font-family: 'Poppins'; font-size: 14px; border-bottom: solid 1px #DDD"> Name </div> <div style="display: flex; padding: 1.2rem; background-color: white"> <div style="display: flex; margin-right: 1.2rem;align-items: center; "> <div style="border-radius: 100%; background-color: #6785C1; height: 13px; width: 13px;"></div> </div> <div style="display: flex; flex-direction: column; font-family: 'Poppins'; font-size: 14px"> <div>Revenue: <span style="font-weight: 600">${currentDataToShow[0].substr(0, currentDataToShow[0].length - 1)}</span></div> <div>Revenue per employee: <span style="font-weight: 600">${currentDataToShow[1].substr(0, currentDataToShow[1].length - 1)}</span></div> <div>Net income per employee: <span style="font-weight: 600">${this.customReportUtilities.parseNumberFunction(Number(currentDataToShow[2]) * 100)}</span></div> </div> </div> </div> `; tooltipEl.querySelector('table').innerHTML = innerHtml; }
Finally we finish configuring the container
const position = context.chart.canvas.getBoundingClientRect();
// Display, position, and set styles for font tooltipEl.style.opacity = '1'; 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.padding = tooltipModel.padding + 'px ' + tooltipModel.padding + 'px'; tooltipEl.style.pointerEvents = 'none';
I have had to use some additional styles as an overflow to make the border-radius show. Chart.js documentation on the subject: https://www.chartjs.org/docs/latest/samples/tooltip/html.html
score:9
As of v2.4, the callbacks unfortunately don't allow for HTML currently. You'll need to write a custom tooltip function.
Examples can be found in the samples folder for chart-js (although some are better than others I found).
https://github.com/chartjs/Chart.js/tree/v2.4.0/samples/tooltips
Try running the samples to get a feel for how the options and modifications affect the tooltip function.
For example in the line chart example of a custom function:
Chart.defaults.global.pointHitDetectionRadius = 1;
var customTooltips = function(tooltip) {
// Tooltip Element
var tooltipEl = document.getElementById('chartjs-tooltip');
if (!tooltipEl) {
tooltipEl = document.createElement('div');
tooltipEl.id = 'chartjs-tooltip';
tooltipEl.innerHTML = "<table></table>"
document.body.appendChild(tooltipEl);
}
// Hide if no tooltip
if (tooltip.opacity === 0) {
tooltipEl.style.opacity = 0;
return;
}
// Set caret Position
tooltipEl.classList.remove('above', 'below', 'no-transform');
if (tooltip.yAlign) {
tooltipEl.classList.add(tooltip.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Set Text
if (tooltip.body) {
var titleLines = tooltip.title || [];
var bodyLines = tooltip.body.map(getBody);
//PUT CUSTOM HTML TOOLTIP CONTENT HERE (innerHTML)
var innerHtml = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach(function(body, i) {
var colors = tooltip.labelColors[i];
var style = 'background:' + colors.backgroundColor;
style += '; border-color:' + colors.borderColor;
style += '; border-width: 2px';
var span = '<span class="chartjs-tooltip-key" style="' + style + '"></span>';
innerHtml += '<tr><td>' + span + body + '</td></tr>';
});
innerHtml += '</tbody>';
var tableRoot = tooltipEl.querySelector('table');
tableRoot.innerHTML = innerHtml;
}
var position = this._chart.canvas.getBoundingClientRect();
// Display, position, and set styles for font
tooltipEl.style.opacity = 1;
tooltipEl.style.left = position.left + tooltip.caretX + 'px';
tooltipEl.style.top = position.top + tooltip.caretY + 'px';
tooltipEl.style.fontFamily = tooltip._fontFamily;
tooltipEl.style.fontSize = tooltip.fontSize;
tooltipEl.style.fontStyle = tooltip._fontStyle;
tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
};
Then set this as the custom tooltip function in the options for the chart:
window.myLine = new Chart(chartEl, {
type: 'line',
data: lineChartData,
options: {
title:{
display:true,
text:'Chart.js Line Chart - Custom Tooltips'
},
tooltips: {
enabled: false,
mode: 'index',
position: 'nearest',
//Set the name of the custom function here
custom: customTooltips
}
}
});
EDIT: Apologies, I only read the title of your question, not the full question. What you ask can be done more simply and without HTML in the tooltips (unless it's required for another reason) by changing the interaction mode to index in the options. There's a sample available to show how this works.
Source: stackoverflow.com
Related Query
- Chart JS Show HTML in Tooltip
- show label in tooltip but not in x axis for chartjs line chart
- chart js tooltip how to control the data that show
- ng2-charts customize data and whole html content of tooltip displayed when hovering on bar chart
- ChartJS: Show all labels of a mixed chart in the tooltip
- ChartJS (React) Line Chart - How to show single tooltip with data and labels from 3 (multiple) dataset?
- Chart JS tooltip appears differently when set from script instead of html
- How to show tooltip value of all data falling on the same axis in chart js?
- ng2-Chart: can we show the tooltip data of pie chart on load?
- How to show tooltip only when data available in chart js?
- Always show doughnut Chart tooltip in Angular 5
- Is there any way to show a tooltip for points which are not visible on the chart in Chart.js?
- Chart tooltip should show the consolidated information of a single bar in double bar chart
- How to always show line chart tooltip in ionic-angular.?
- Getting the HTML code of a chart created by chart.js
- Chart JS 2.x: How to show a tooltip in a timeline chart?
- Chart.js Show labels on Pie chart
- ChartJS New Lines '\n' in X axis Labels or Displaying More Information Around Chart or Tooltip with ChartJS V2
- chart.js: Show labels outside pie chart
- Chart JS custom tooltip option?
- Chart.js how to show cursor pointer for labels & legends in line chart
- chart.js scatter chart - displaying label specific to point in tooltip
- Chart.js doughnut chart tooltip size?
- chartjs show dot point on hover over line chart
- ChartJS Line Graph - Multiple Lines, Show one Value on Tooltip
- ChartJS add tooltip to a grouped bar chart
- Html chart does not fit a small Android WebView
- How to show percentage (%) in chart js
- Show X axis on top and bottom in line chart rendered with Chart.js 2.4.0
- Adding Chart.js line chart to Jinja2/Flask html page from JS file
More Query from same tag
- How to use two Y axes in Chart.js v2?
- ChartJS: Show default tooltip onclick
- Using Google Analytics raw data to display graph by month
- Hide/disable tootlip on specific graph values
- How to add Dyamic JSON Dropdown Menu in Angular JS
- chart.js radar pointLabel options not working
- Configuring ChartJS from VB.NET
- Set height of chart in Chart.js
- Chart.js drawing line between two points
- Unable to clone a Chart.js chart in a pop up
- Chart JS not reloading in Partial View
- Chart.js - Show new data on button click
- Problems trying to render some data on chartjs
- chart js put meter square / superscript on y axis
- Draw borders on line chartjs
- How to create a stacked graph using ChartJS
- ChartJS show jittering on hover
- Vue Chart.js Doughnut Chart with rounded and spaced arcs (vue3-chart-v2)
- How to change orientation of the main y-axis label in charts.js?
- How to expand the "Y" scale of the data in chart.js?
- Why the bar are not aligned the y axis
- Chartjs: How can I group datasets closer if I have maxBarThickness set?
- Chart.js not rendering unless i set a timeout
- How to add faded background to stack chart in react native
- Chart.js: hiding series by clicking on legend
- Chart.js ignoring canvas height & width
- CoreUI Chart type Bar- clickable bars to link to another page
- How to pass sql query data onto the datasets field of chartjs using nodejs (ejs)
- Change style of hover and tooltip in chartjs or ng2-charts
- Line chart Change background color of shaded region on hover (Chartjs)