score:3
You can create a helper function and check whenever the DOM element exists for the barChartX
, dnutChartY
, dnutChartZ
or any other DOM element like this:
var doChart = function(o, d) {
if (typeof(o) != 'undefined' && o.length > 0) {
return new Chart(o, d);
} else {
return null;
}
}
Then your Chart.js code will be like this
// *************************************
// Chart.js
// *************************************
// Global Settings
Chart.defaults.global.defaultFontColor = "rgba(43,43,43,1)";
Chart.defaults.global.defaultFontFamily = "'ApexNew-Medium', 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
Chart.defaults.global.defaultFontSize = 12;
Chart.defaults.global.defaultFontStyle = "normal";
Chart.defaults.global.maintainAspectRatio = false;
// Disable click on legend
Chart.defaults.global.legend.onClick = (e) => e.stopPropagation();
var doChart = function(o, d) {
if (typeof(o) != 'undefined' && o.length > 0) {
return new Chart(o, d);
} else {
return null;
}
}
// Bar Charts settings
var barChart__options = {};
// Doughnut settings
var dnutChart__options = {
legend: {
position: "bottom",
// Disable click on legend
onClick: (e) => e.stopPropagation()
}
};
// *************************************
// Datasets
// *************************************
// Bar Chart X
var barChartX__data = {
labels: ["Alpha", "Bravo", "Charlie"],
datasets: [{
label: "2015",
borderWidth: 0,
backgroundColor: "rgba(43,43,43,1)",
data: [410, 430, 110]
},
{
label: "2016",
borderWidth: 0,
backgroundColor: "rgba(233,131,0,1.0)",
data: [405, 360, 150]
}
]
};
const barChartX = $("#barChartX");
/*let ChartX = new Chart(barChartX, {
type: "bar",
data: barChartX__data,
options: barChart__options
});*/
let ChartX = doChart(barChartX, {
type: "bar",
data: barChartX__data,
options: barChart__options
});
// Doughnut Chart Y
var dnutChartY__data = {
labels: ["Alpha", "Bravo"],
datasets: [{
label: "Points",
borderWidth: 0,
backgroundColor: ["rgba(43,43,43,1)", "rgba(233,131,0,1.0)"],
data: [90, 270]
}]
};
const dnutChartY = $("#dnutChartY");
let ChartY = doChart(dnutChartY, {
type: "doughnut",
data: dnutChartY__data,
options: dnutChart__options
});
// Doughnut Chart Z
var dnutChartZ__data = {
labels: ["Alpha", "Bravo", "Charlie"],
datasets: [{
label: "Points",
borderWidth: 0,
backgroundColor: ["rgba(233,131,0,1.0)", "rgba(239,162,64,1.0)", "rgba(244,193,127,1.0)"],
data: [405, 360, 150]
}]
};
const dnutChartZ = $("#dnutChartZ");
let ChartZ = doChart(dnutChartZ, {
type: "doughnut",
data: dnutChartZ__data,
options: dnutChart__options
});
Please check my working example with no javascript errors here: http://zikro.gr/dbg/html/chartsjs/
UPDATE
Please have a look at the JSFiddle example here: https://jsfiddle.net/h1dafqjx/2/
UPDATE 2
Problem analysis and solution
The problem you are facing, is that you want to have multiple declarations and chart setups in one javascript file that you are going to use on many location which may happen some of these locations do not have some of the declared elements, thus you want your code to handle those cases.
You declare a chart like this:
const barChartX = $("#barChartX");
let ChartX = new Chart(barChartX, {
type: "bar",
data: barChartX__data,
options: barChart__options
});
In order to handle a missing DOM element, like when the $("#barChartX")
does not exists, you need to create a condition to check those cases.
For excample:
const barChartX = $("#barChartX");
if(typeof(barChartX) != 'undefined' && barChartX.length > 0) {
let ChartX = new Chart(barChartX, {
type: "bar",
data: barChartX__data,
options: barChart__options
});
}
With the obove code, you check if the barChartX
is defined and if it actually contains any elements with the barChartX.length > 0
condition.
Now, in order to do not repeat things, we keep it simple and do all that checking in a function. Thus we create the function doChart
like this:
var doChart = function(o, d) {
if (typeof(o) != 'undefined' && o.length > 0) {
return new Chart(o, d);
} else {
return null;
}
}
The first parameter o
is the DOM element we want to check and the second parameter d
is the chart object properties.
For example:
let ChartX = doChart(barChartX, {
type: "bar",
data: barChartX__data,
options: barChart__options
});
Here we pass to the doChart
function the barChartX
jQuery object of the element in order for the function to check if exists. Then we pass the chart object parameters by the second parameter named d
, which is the chart object properties for creating the new chart:
{
type: "bar",
data: barChartX__data,
options: barChart__options
}
Source: stackoverflow.com
Related Query
- How do I keep chart.js charts in one JS file, and not get errors when the ID from the JS file don't exist on one specific html page?
- How do i have a single Chart.vue component instead of different chart components and then display charts from it by changing id of the API
- How to get a value from function javascript and print it to the chart
- How to get the actual chart width and height in chart.js
- How to get chart from data points (arrays) with inconsistent time intervals and chart.js?
- How do I customize y-axis labels and randomly pick the value from the data range for x-axis in Chart js
- how can i use chart.js to create a chart that has one time series line and one linear line on it at the same time?
- How to reuse a Chartjs Chart component in with different Data and get past the **Canvas is already in use** error?
- chart.js one of the chart from mixed chart is not plotting
- Angular6 and ng2-charts does not display any charts when i fill data from webservice
- How to add left padding for my charts done in ChartJs and my Google Map so it is not glued to the limit of the page on the left
- How to start the chart from specific time and offest hour and then show the data on chart from target datetime in chartjs
- How can I remove the white border from Chart.js pie chart when all legends are hidden?
- How to increase the size of the donut or pie chart and keep the legend next to it in chart JS?
- How do I get the current step size of a chartjs chart whose stepSize I have not defined?
- Chart js: I'm getting the labels crossed on my pieChart and doughnut. Not able to get the chart itself
- Chart is not populating when getting the data from AJAX call
- How do you get the width of a datalabel from the Chartjs plugin after the chart animates?
- I am using chart js to draw a chart. I did everything right but i don't know why the x axis and y axis label is not comming in chart. code below
- How to limit chart JS hover to take only one value from each line chart when zoomed out?
- Chart.js 3.6.2, Angular 10: Logarithmic Line chart Y-Axis problems. How to set and keep Y-Axis properties, even when data changes?
- How to set the data of chart in angular which is taken from the backend nodejs api that is store in mongodb and showing on the html page
- how I can get label name when user click on particular area in doughnut chart.js? I am not able to find the index of selected area for chart.js
- Chart.js returns a console error and does not display the chart when using variables as data input
- chart.js - how to draw and manage line when only one label present in chart js Linechart
- Get data from SQLite as an array and generate charts with the data using Chart.js in an HTML
- How to get 2 doughnut charts in one chart (chartjs)
- How can i get the Chart JS Bar Graph Bar Label and Value on click?
- how to not repeat code while creating multiple charts in chart js
- How do I increase the space between the Legend and the Chart when using angular-chart.js?
More Query from same tag
- Chart.JS change Text Color
- Why ChartJS's Bar Chart does not render bar for a specific value?
- How using charts.js with JSON?
- Chartjs + moment() not displaying on django
- Ajax asynchronicity calls end function before inner loop function
- How to set Solid label in bar chart using Chart JS
- How to loop over Chart.js with Django list view
- Chart.js adds unwanted padding on top and below chart with padding set to 0
- ChartJS rotate label value vertical
- ChartJS - Bottom labels displayed vertically
- How to Create a Custom Logarithmic Axis in Chart.js
- “lazy-initialize” In ChartJS
- How to show gradient vertically on chart js grouped bar chart?
- Change Chart JS Bar Chart Border to Dotted Line
- Bootstrap tab is working but the tab content is not showing
- Angular: chart.js chart is not displaying
- Chart.js won't draw the line on chart line
- How can i get the Chart JS Bar Graph Bar Label and Value on click?
- HTML/Chart JS deserialize JSON from Python Flask
- How to edit the ID of each button in a class if a condition is true in JavaScript?
- Chart js - Customize chart
- Draw Line Chart Using Chart.js
- ChartJS -- How do I change scale color when I have to scales?
- Click on chart to expand more information - Chart.js
- chartJS, how to disable user from clicking on legend names and changing the graph?
- How do I use Chart.js and Bootstrap at same time? (various jQuery versions)
- Chart.js - Shift/Stagger labels horizontally (for x axis) instead of rotating
- Populating a chartJS with data from API through axios (VueJS)
- How to display inline values in a stacked bar chart with Chart.js?
- Async showing data in pieChart from chart.js with typescript