question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Show/Hide chart by click custom legend

See original GitHub issue

Hello! Thanks for this very cool library! My question is how it is possible to repeat functionality for show/hide chart for custom legend? Yes, this functionality working for charts by default. But I have to change default legend to custom and lost show/hide function.

I made a default legend hidden and generate my own like this:

var weightChartOptions = {
    responsive: true,
    legendCallback: function(chart) {
        var legendHtml = []; 
        legendHtml.push('<table>');
        legendHtml.push('<tr>');
        for (var i=0; i<chart.data.datasets.length; i++) {
            legendHtml.push('<td><div class="chart-legend" style="background-color:' + chart.data.datasets[i].backgroundColor +'"></div></       td>');  
            if (chart.data.datasets[i].label) {
                legendHtml.push('<td class="chart-legend-label-text">' + chart.data.datasets[i].label + '</td>');
            }
        }
        legendHtml.push('</tr>');
        legendHtml.push('</table>');
        return legendHtml.join("");
    },
    legend: {
        display: false
    }
};

var ctx = document.getElementById("weightChart").getContext("2d");
var weightChart = new Chart(ctx, {
    type: 'line',
    data: weightChartData,
    options: weightChartOptions
});
document.getElementById("weightChartLegend").innerHTML = weightChart.generateLegend();

How I can keep this custom legend and add show/hide function? Thanks.

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:11
  • Comments:12 (5 by maintainers)

github_iconTop GitHub Comments

14reactions
achirkofcommented, May 16, 2016

Git it! Thank you very much!

var weightChartOptions = {
        responsive: true,
        legendCallback: function(chart) {
            console.log(chart);
            var legendHtml = [];
            legendHtml.push('<table>');
            legendHtml.push('<tr>');
            for (var i=0; i<chart.data.datasets.length; i++) {
                legendHtml.push('<td><div class="chart-legend" style="background-color:' + chart.data.datasets[i].backgroundColor + '"></div></td>');                    
                if (chart.data.datasets[i].label) {
                    legendHtml.push('<td class="chart-legend-label-text" onclick="updateDataset(event, ' + '\'' + chart.legend.legendItems[i].datasetIndex + '\'' + ')">' + chart.data.datasets[i].label + '</td>');
                }                                                                              
            }                                                                                  
            legendHtml.push('</tr>');                                                          
            legendHtml.push('</table>');                                                       
            return legendHtml.join("");                                                        
        },                                                                                     
        legend: {                                                                              
            display: false                                                                     
        }                                                                                      
    };                                                                                         

    // Show/hide chart by click legend
    updateDataset = function(e, datasetIndex) {
        var index = datasetIndex;
        var ci = e.view.weightChart;
        var meta = ci.getDatasetMeta(index);

        // See controller.isDatasetVisible comment
        meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;

        // We hid a dataset ... rerender the chart
        ci.update();
    };

    var ctx = document.getElementById("weightChart").getContext("2d");
    window.weightChart = new Chart(ctx, {
        type: 'line',
        data: weightChartData, 
        options: weightChartOptions
    });
    document.getElementById("weightChartLegend").innerHTML = weightChart.generateLegend();
};

The most important parts are:

onClick function call for each legend label

if (chart.data.datasets[i].label) {
    legendHtml.push('<td class="chart-legend-label-text" onclick="updateDataset(event, ' + '\'' + chart.legend.legendItems[i].datasetIndex + '\'' + ')">' + chart.data.datasets[i].label + '</td>');
}

and function

updateDataset = function(e, datasetIndex) {
    var index = datasetIndex;
    var ci = e.view.weightChart;
    var meta = ci.getDatasetMeta(index);

    // See controller.isDatasetVisible comment
    meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;

    // We hid a dataset ... rerender the chart
    ci.update();
};

Also make chart instance of Window adding window. before:

window.weightChart = new Chart(ctx, {
        type: 'line',
        data: weightChartData, 
        options: weightChartOptions
});
3reactions
GeraudWillingcommented, Jan 23, 2018

I’m actually facing a similar issue. I"ve make a custom legend component and I’m able to show/hide using the above codes. However, this only works for bar chart. It raise the following exception when using it with donut chart:

TypeError: Cannot read property '_meta' of undefined at Chart.getDatasetMeta (core.controller.js:656)

Have anyone faced a similar issue please?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Chart js show/hide legend during runtime via buttonClick
js) by clicking a button. I tried this so far: The following code changes the value of scatterChart.legend.options.display but after executing ...
Read more >
How to Create Custom Legend for Doughnut Chart ... - YouTube
How to Create Custom Legend for Doughnut Chart that Show Hide Datasets in Chart JSIn this video we will explore how to create...
Read more >
Chart js show/hide legend - Javascript
<html lang="en"> <head> <title>Chart.js - Hide/Show Legend From Button Click</title> </head> <body translate="no"> <div style="width:45%;"> <canvas ...
Read more >
Show / Hide series on legend click
That said, you can create a custom legend and handle the onclick event of its elements to show/hide the corresponding series.
Read more >
Hide Unhide Data Series in Chart on Legend Click
How to hide/unhide data series on click of legend items – in case of multi series chart. CanvasJS supports setting the visibility of...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found