CanvasJS Charts in Tabs
by canvasjs
HTML
<script src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
<div class="tabs">
<button class="tab-button active" data-tab="tab1">Tab 1 - Line Chart</button>
<button class="tab-button" data-tab="tab2">Tab 2 - Pie Chart</button>
</div>
<div id="tab1" class="tab-content" style="display: block;">
<div id="chartContainer1" class="chart-container"></div>
</div>
<div id="tab2" class="tab-content">
<div id="chartContainer2" class="chart-container"></div>
</div>
CSS
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.tabs {
overflow: hidden;
border-bottom: 1px solid #ccc;
}
.tab-button {
background-color: #f1f1f1;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
}
.tab-button:hover {
background-color: #ddd;
}
.tab-button.active {
background-color: #ccc;
}
.tab-content {
display: none;
padding: 20px;
border: 1px solid #ccc;
border-top: none;
}
.chart-container {
height: 400px;
width: 100%;
}
JavaScript
var chart1 = new CanvasJS.Chart('chartContainer1', {
animationEnabled: true,
theme: 'light2',
title: {
text: 'Line Chart',
},
data: [
{
type: 'line',
dataPoints: [
{ x: 10, y: 71 },
{ x: 20, y: 55 },
{ x: 30, y: 50 },
{ x: 40, y: 65 },
{ x: 50, y: 95 },
{ x: 60, y: 68 },
{ x: 70, y: 28 },
{ x: 80, y: 34 },
{ x: 90, y: 14 },
],
},
],
});
chart1.render();
var chart2 = new CanvasJS.Chart('chartContainer2', {
animationEnabled: true,
theme: 'light2',
title: {
text: 'Pie Chart',
},
data: [
{
type: 'pie',
showInLegend: true,
legendText: '{label}',
dataPoints: [
{ label: 'Apple', y: 30 },
{ label: 'Orange', y: 20 },
{ label: 'Banana', y: 25 },
{ label: 'Mango', y: 15 },
{ label: 'Grape', y: 10 },
],
},
],
});
document.querySelectorAll('.tab-button').forEach((button) => {
button.addEventListener('click', () => {
document.querySelectorAll('.tab-content').forEach((tab) => {
tab.style.display = 'none';
});
document.querySelectorAll('.tab-button').forEach((btn) => {
btn.classList.remove('active');
});
const tabId = button.getAttribute('data-tab');
document.getElementById(tabId).style.display = 'block';
button.classList.add('active');
if (tabId === 'tab1') {
chart1.render();
} else if (tabId === 'tab2') {
chart2.render();
}
});
});