user1283776
user1283776

Reputation: 21764

Remove series from chart when user clicks on legend?

You should know that I am new to Highcharts, so if my code or question seem weird, let me know.

Users can add data series to a chart.

When users click on the legend of a data series, that data series get's hidden from the chart and the legend get's grayed out. I want to change this behavior so that when users click on the legend of a data series, that data series should be completely removed from the chart, not only hidden.

I tried by writing the following code in highcharts-graph.js:

plotOptions: {
                line: {

                    events: {
                        legendItemClick: function () {
                            this.remove(true);
                        }
                    }
                }
            }

This code removes the legend. But when a user adds another data series to the chart, the legend of the deactivated data series re-appears. So I believe that I need to modify the code to remove the data series instead of the legend.

Upvotes: 0

Views: 731

Answers (1)

Kacper Madej
Kacper Madej

Reputation: 7886

To avoid error being thrown legendItemClick function could return false. To avoid same names or mixed indexes for series, it is possible to set names and indexes for new series.

JSFiddle: http://jsfiddle.net/jct0msdt/

$(function () {
    $('#container').highcharts({
        plotOptions: {
            line: {
                events: {
                    legendItemClick: function () {
                        this.remove(true);
                        return false;
                    }
                }
            }
        },
        series: [{
            data: [1, 2, 3, 4, 5, 6, 7]
        }, {
            data: [3, 4, 5, 6, 7]
        }, {
            data: [2, 3, 4, 5, 6, 7]
        }, {
            data: [4, 5, 6, 7, 8, 9]
        }]
    });

    var i = 5,
        chart = $('#container').highcharts();
    $('#button').click(function () {
        chart.addSeries({
            data: [i, i + 2, i + 4],
            index: i,
            name: 'Series ' + i
        });
        i++;
    });
});

Upvotes: 3

Related Questions