Custom HTML tooltips

The Chart.defaults.global.tooltips.custom (or options.tooltips.custom) property receives a function that should build an HTML tooltip and connect it to a tooltip model object passed as a parameter. The tooltip model is a native object that responds to tooltip events and stores tooltip properties. Its properties can be copied and reused inside the HTML tooltip if desired.

The following example (Tooltips/tooltip-7-custom.html) shows how to create a simple custom HTML tooltip containing an image. The custom tooltip can be created using HTML as shown in the following snippet, or programmatically using DOM, and should initially be hidden (opacity: 0). When a hover event activates a tooltip, the model’s opacity changes and the custom tooltip uses this state to make itself visible:

<html><head> ...
<style>
#tooltip {
opacity: 0;
position: absolute;
margin: 5px;
}
</style>
</head><body>
<canvas id="chart" width="200" height="100"></canvas>
<div id="tooltip"></div>
<script>
const data = {
labels: ["jupiter", "saturn", "uranus", "neptune"],
datasets: [{
data: [142984,120536,51118,49528],
backgroundColor: ['#d7191c','#fdae61','#abdda4','#2b83ba'],
}]
};
new Chart('chart', { type: 'bar', data: data,
options: {
legend: { display: false },
title: {
display: true,
text: 'Planetary diameters',
fontSize: 24
},
tooltips: {
mode: 'index',
intersect: true,
enabled: false, // turn off canvas tooltips
custom: function(model) {
const tooltip = document.getElementById('tooltip');
if(model.opacity === 0) {
tooltip.style.opacity = 0;
return; }
if(model.body) {
const value = model.body[0].lines[0];
tooltip.innerHTML = '<b>'+ value + " km<br/>"
+'<img width="50"
src="../Images/'
+model.title[0] +'.jpg"
</img>';
const pos =
this._chart.canvas.getBoundingClientRect();
tooltip.style.opacity = 1;
tooltip.style.left = pos.left + model.caretX +
'px';
tooltip.style.top = -50 + pos.top +
model.caretY + 'px';
}
}
}
}
});
</script>
</body></html>

The code extracts the title and filename from the tooltip model’s title, and the value from the model’s body. The custom tooltip also used the model’s coordinates to decide where it would be placed. The result is as follows. If you hover over the labels in the x-axis or the bars, the HTML tooltip will be shown above each bar:

Bar chart with a custom HTML tooltip that appears when the mouse hovers over a bar or label. Code: Tooltips/tooltip-7-custom.html.

Positioning tooltips in pie charts is a bit more complex. For more examples on how to create custom HTML tooltips, check the samples page in the official documentation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset