Chartjs-Chart.js sciptable options: accessing the values of the data object?

2👍

I can’t tell you why it’s not working but you can change the following line inside the the scriptable function.

from:

var value = context.dataset.data[index].temper; 

to:

var value = context.dataset.data[index]?.temper;

The problem is that context.dataset.data[index] sometimes results in undefined.

Please take a look at your amended code below:

new Chart('myChart', {
  type: 'line',
  data: {
    datasets: [{
      label: "Line Graph",
      data: [{
        'time': '08h00',
        'magnitude': 25,
        'temper': 12.6
      }, {
        'time': '09h00',
        'magnitude': 39,
        'temper': 5.3
      }],
      parsing: {
        xAxisKey: 'time',
        yAxisKey: 'temper'
      },
      borderColor: function(context) {
        var index = context.dataIndex;
        var value = context.dataset.data[index]?.temper;
        return value > 10 ? 'red' : 'green';
      }
    }]
  },
  options: {
    scales: {
      x: {
        type: 'time',
        time: {
          parser: 'HH\hmm',
          unit: 'day',
        },
      },
    },
    responsive: 'true'
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.27.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@0.1.1"></script>
<canvas id="myChart"></canvas>

Leave a comment