Reputation: 10724
I use Chart.js (in last version 2.7), and if I have multiple charts on my page, I have an issue with the tooltip.
On this fiddle : https://jsfiddle.net/b4up8kw2/, I have 2 charts, but if you look, the tooltip of the first chart (on left) shows the values of the second chart.
I use this code to update the dataset of the charts :
var configs = [];
var charts = [];
configs['chart1'] = config;
configs['chart2'] = config;
// update chart - randomScalingFactor() return random integer
function updateChart(chart) {
// set new values
configs[chart].data.datasets.forEach(function(dataset) {
dataset.data = [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
});
charts[chart].update();
}
$(function() {
charts['chart1'] = new Chart($('#canvas-1')[0].getContext('2d'), configs['chart1']);
charts['chart2'] = new Chart($('#canvas-2')[0].getContext('2d'), configs['chart2']);
for (var key in charts) {
updateChart(key);
}
});
I don't understand since I use 2 separate configs variables. Is it a bug of my code or of the plugin ?
Upvotes: 0
Views: 952
Reputation: 1838
I've solved your problem with clone
your config for each chart. Currently, you render charts with one object config
, which is shared and when render second chart, the config is changed. So you should clone config for each chart.
This is my solution (forked and edited from your jsfiddle) https://jsfiddle.net/huynhsamha/bdvw1e98/
const clone = (o) => JSON.parse(JSON.stringify(o))
var configs = {
chart1: clone(config),
chart2: clone(config)
};
<script async src="//jsfiddle.net/huynhsamha/bdvw1e98/embed/js,html,css,result/dark/"></script>
Upvotes: 4