[Chartjs]-Chart js custom separate legend returns error when clicking legend

1👍

You need to invoke getDatasetMeta(index) on your chart object.

Instead of this…

var meta = ci.getDatasetMeta(0);

try this:

var meta = myDarkRadarChart.getDatasetMeta(0);

UPDATE

I see that there are other problems as well, the main one is that you always getDatasetMeta() with index 0 but you should use the index of the dataset you’re going to hide or show again. The updateDatasetGraphs() could be simplified as follows:

function updateDatasetGraphs(e, datasetIndex) {
  var meta = myDarkRadarChart.getDatasetMeta(datasetIndex);
  meta.hidden = !meta.hidden;  
  if (meta.hidden) {   
    $('#' + e.path[0].id).css('color', '#cbd0d5');
  } else {
    $('#' + e.path[0].id).css('color', '#000');    
  }
  myDarkRadarChart.update();
};

Please have a look at your amended code below:

var myDarkRadarChart = new Chart('weeklyHoursGraph', {
  type: 'line',
  data: {
    labesl: ['A', 'B', 'C', 'D', 'E'],
    datasets: [{      
      data: [2, 4, 6, 1, 3],
    },
    {      
      data: [4, 5, 7, 5, 4],
    }
    ]
  },
  options: {
    legend: {
      display: false
    }    
  }
});

function updateDatasetGraphs(e, datasetIndex) {
  var meta = myDarkRadarChart.getDatasetMeta(datasetIndex);
  meta.hidden = !meta.hidden;  
  if (meta.hidden) {   
    $('#' + e.path[0].id).css('color', '#cbd0d5');
  } else {
    $('#' + e.path[0].id).css('color', '#000');    
  }
  myDarkRadarChart.update();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<div class="legend-container">
  <div class="graph_legend">
    <a id="weekly-legend-0-item" onclick="updateDatasetGraphs(event,0)">This Week</a>
    <a id="weekly-legend-1-item" onclick="updateDatasetGraphs(event,1)">Last Week</a>
  </div>
</div>
<div class="graph">
  <canvas height="100" id="weeklyHoursGraph"></canvas>
</div>

Leave a comment