My requirement is to display multiple charts with common x-axis. And have x-axis label enabled only for the last chart shown (as they are common).
In the fiddle https://jsfiddle.net/1dhLut64/, My code creates four charts at the beginning even if only one chart is selected (You could see updateCharts
method called four times). How do I create a chart for the first time only if it is visible. i.e. only when I click the chart2 checkbox, chart2 should be created. This way I believe performance can be improved. Thank you.
Update method below:
// calls other functions, including updatecharts
setTimeout(chartLoaded, 0);
// To have xAxis label enabled for the last chart selected.
function updateCharts() {
console.log("updatecharts called")
const selected = Highcharts.charts.map(chart =>
document.querySelector(`#checkbox${chart.options.id}`).checked);
const checkedCheckboxes = selected.filter(x => x).length; // counts true values in selected
const lastSelected = selected.lastIndexOf(true); // the last index of true
Highcharts.charts.forEach(function(chart, i) {
chart.update({
chart: {
height: height / checkedCheckboxes
},
xAxis: {
labels: {
enabled: i === lastSelected
}
}
});
});
}
CodePudding user response:
You can for example store all of the required chart information in an array:
const chartsInfo = [{
container: 'chart1',
title: 'NorthAmerica1',
data: data
}, ...];
Create only the first chart at the beginning and on select create the next one if not already exist:
document.querySelectorAll('#checkboxes input').forEach(function(checkbox, index) {
checkbox.addEventListener('change', (e) => {
const id = e.target.dataset.id,
checked = e.target.checked,
node = document.querySelector(`#chart${id}`);
if (!charts[index]) {
const newChart = new Chart(
chartsInfo[index].container,
index 1,
chartsInfo[index].title,
chartsInfo[index].data
);
charts[index] = newChart.create();
}
if (checked) {
node.style.display = 'block';
} else {
node.style.display = 'none';
}
updateCharts();
});
});
Live demo: https://jsfiddle.net/BlackLabel/xuf6293k/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#Chart