Highcharts add 3 buttons Hide/Remove/Settings to Legend

Viewed 447

I would like to add 3 buttons(Hide/Remove/Settings) to the Legend:

  1. Hide button should have onclick event to hide series/indicator,
  2. Remove button should have onclick event to remove(not hide) series/indicator,
  3. Settings button should have onclick event to show popup for edit settings of the series/indicator.

Code:

legend: {
  enabled: true,
  useHTML:true,
  labelFormatter: function () {
    return this.name + ' <button onclick="indicator_hide()">Hide</button>' + '<button onclick="indicator_remove()">Remove</button>' + '<button onclick="indicator_settings()">Settings</button>';
}

Code for button

function indicator_hide(){
  if(chart.series[0].visible==true){ 
    chart.series[0].visible=false
  } else{
    chart.series[0].visible=true
  }
}

I created a chart, see the link below.

jsFiddle https://jsfiddle.net/PaulJaker/7bLdjs4y/1/

1 Answers

It is easier to connect the click events with a series if you use load chart event to add event listeners. Then it is enough to call the right methods for a series.

chart: {
  events: {
    load: function() {
      this.legend.allItems.forEach(item => {
        const btns = item.legendItem.element.children;

        btns[0].addEventListener('click', () => indicator_hide(item));
        btns[1].addEventListener('click', () => indicator_remove(item));
        btns[2].addEventListener('click', () => indicator_settings(item));
      });

      document.getElementById('popupClose').addEventListener('click', function() {
        this.parentElement.style.visibility = "hidden";
      });
    }
  }
},
legend: {
  enabled: true,
  useHTML: true,
  labelFormatter: function() {
    return this.name + ' <button>Toggle</button>' +
      '<button>Remove</button>' +
      '<button>Settings</button>';
  }
}

Live demo: https://jsfiddle.net/BlackLabel/bu53n1sc/

API Reference: https://api.highcharts.com/highcharts/chart.events.load

Related