My code works perfectly in Codepen, but once I started working with it locally I keep getting a "Chart isn't declared error". Not sure if its my HTML structure or Javascript. Codepen JS doesn't appear to show signs of a problem.
JS:
var canvas = document.getElementById("barChart");
var ctx = canvas.getContext('2d');
Chart.defaults.global.defaultFontColor = 'dodgerblue';
Chart.defaults.global.defaultFontSize = 16;
var data = {
labels: ["Vanilla", "Chocolate", "Strawberry","Carmel", "Tripple
Chocolate"],
datasets: [
{
label: "Ice Cream Sales ",
fill: true,
backgroundColor: [
'moccasin',
'saddlebrown',
'lightpink',
'gold',
'saddlebrown'],
data: [15, 14, 10, 6, 2]
}
]
};
var options = {
title: {
display: true,
text: 'Items Sold',
position: 'bottom'
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
HTML:
<!DOCTYPE html>
<html>
<meta charset="utf-8"/>
<head>
<link rel="stylesheet" href="graph1.css" type="text/css">
</head>
<body>
<div class="container">
<br />
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<canvas id="barChart"></canvas>
</div>
<div class="col-md-1"></div>
</div>
</div>
<script src="graph1.js"></script>
</body>
</html>
Codepen link: https://codepen.io/ksav22/pen/dLmdqM
That's because in codepen, you have this script attached ("Open JS Settings" modal):
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.min.js
Without it, Chart
is undefined.
You need to link to it in your HTML (and before your own script using Chart).
You also need to wait until all the files are loaded before executing your JS code. All of your procedural code should be in the document.addEventListener("DOMContentLoaded", function(event) {});
anonymous function. Otherwise, if your script is loaded before chart.js is loaded, it will say that "chart is undefined" because it hasn't been loaded yet!
Your user-defined functions and global variable declarations should be outside of the document.addEventListener("DOMContentLoaded", function(event) {});
function, however.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.