1👍
✅
you should move the chart code inside the openTab
and use a global variable as a flag to see if the chart is loaded once then dont load it again see the codepen or demo below
// function to switch between tabs
var isLoaded = false;
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
if (tabName == 'tabThree' && !isLoaded) {
isLoaded = true;
// Working Chart.js
console.log('loaded');
var ctx = document.getElementById("test-chart").getContext('2d');
var newTestChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["10/21", "10/22", "10/23", "10/24", "10/25", "10/26", "10/27", "10/28", "10/29", "10/30", "10/31", "11/01", "11/02", "11/03", "11/04"],
datasets: [{
data: [150, 550, 500, 880, 200, 100, 102, 102, 99, 105, 100, 103, 100, 102, 100],
backgroundColor: ['rgba(77, 112, 144, 0.4)', ],
borderColor: ['rgba(77, 112, 144,1)', ],
borderWidth: 2
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
defaultFontFamily: "'Titillium Web'",
defaultFontSize: 16,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
}
});
}
}
document.getElementById("defaultOpen").click();
body {
font-family: sans-serif;
}
div.tab button {
border: none;
outline: none;
cursor: pointer;
border-radius: 1px;
padding: 0.6em 1em;
flex-basis: 12%;
color: #34495E;
letter-spacing: 1px;
text-transform: capitalize;
font-size: 0.9em;
background-color: #BDC3C7;
}
div.tab button.active {
background-color: #34495E;
color: #fff;
}
.tabcontent {
display: none;
height: 300px;
width: 50%;
color: #fff;
padding: 35px;
}
#tabOne {
background-color: #E74C3C;
}
#tabTwo {
background-color: #3498DB;
}
#tabThree {
text-align: center;
}
#tabFour {
background-color: #2ECC71;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<div class="tab">
<button id="defaultOpen" class="tablinks" onclick="openTab(event, 'tabOne')">Tab One</button>
<button class="tablinks" onclick="openTab(event, 'tabTwo')">Tab Two</button>
<button id="chartTrigger" class="tablinks" onclick="openTab(event, 'tabThree')">Tab Three</button>
<button class="tablinks" onclick="openTab(event, 'tabFour')">Tab Four</button>
</div>
<div id="tabOne" class="tabcontent">
Click Tab Three for Chart
</div>
<div id="tabTwo" class="tabcontent">
</div>
<div id="tabThree" class="tabcontent">
<canvas id="test-chart" height="500"></canvas>
</div>
<div id="tabFour" class="tabcontent">
</div>
Source:stackexchange.com