[Chartjs]-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?

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
}

Leave a comment