[Chartjs]-TypeError: Cannot read property 'currentStyle' of null in chart.js

8👍

HTML:

<div id="line_chart" style="padding-bottom: 20px;">               
 <canvas id="chartJSContainer" height="100"></canvas>
</div>

JS :

$('#chartJSContainer').remove();
$('#line_chart').html('<canvas id="chartJSContainer" height="100"></canvas>'); 
var linectxx = document.getElementById('chartJSContainer').getContext('2d');
var newlinechart = new Chart(linectxx, options1);

Its working for me. Used .html() instead of .append 🙂

0👍

I solve this problem puting the canvas inside a div, like:

<div style="width:75%;">
    <canvas id="canvas"></canvas>
</div>

or in JS:

var div = document.createElement('div');
div.style = "width:100%;";
canvas = document.createElement('canvas');
div.appendChild(canvas);

0👍

The solution of Marcio Rossato did not work for me but this one did :

See here the answer of Valentin : Solution for “Cannot read property ‘currentStyle’ of null in ChartJS”

I downloaded the file and modified it, no error occures now 🙂

0👍

This situation could be caused by many factors.
That said, in my case, it was caused by not having destroyed previous instances of charts that my code had instantiated.

Chart JS automatically binds an event to handle the resize of your chart when you resize your browser window. When you replace your old chart with a new one without destroying the old object, or refreshing the page, the events previously set keep listening and executing, pointing to an element which reference does not exists anymore, causing an attempt to read a property from an object that no longer exists.

So, to solve this, you must destroy your chart with the proper method before replacing it.
Example:

var myChart;
function loadMyChart() {
    if(myChart) myChart.destroy(); // Destroys the previous chart, if it exists.
    
    $('#myChart').replaceWith('<canvas id="myChart"></canvas>');

    $.get("/MyBackEnd/GetMyChart?param1=" + $("#param1").val(), function (data) {
        myChart = new Chart(document.getElementById("myChart"), myChartOptions);
    });
}

Leave a comment