4

I am trying to activate/deactivate a chart line using an HTML button in ECharts js. I do not want to use the ECharts legend to perform this action. I want this HTML button to have this functionality. How is that possible? Thank you!

This is my code:

<html>
<script src="https://cdn.jsdelivr.net/npm/echarts@4/dist/echarts.min.js?_v_=1607268016278"></script>
<link href="https://getbootstrap.com/docs/5.0/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="form-check" style="margin-left: 100px;">
  <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
  <label class="form-check-label" for="flexCheckDefault">
    Activate & Deactivate line
  </label>
</div>

<div id="benchmark" style="min-height:500px;"></div>

<script>
var myChart = echarts.init(document.getElementById('benchmark'));
option = {
    xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
        type: 'value'
    },
    series: [{
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        type: 'line'
    }]
};
myChart.setOption(option);
</script>

</html>

jsfiddle

costastg
  • 139
  • 1
  • 6

2 Answers2

2

var myChart = echarts.init(document.getElementById('benchmark'));
var chartData = [820, 932, 901, 934, 1290, 1330, 1320];
var option = {
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [{
    symbol: 'none',
    id: 'chartLine',
    lineStyle: { color: 'red'},
    data: chartData,
    type: 'line'
  }]
};

myChart.setOption(option);

// 
var checkbox = document.body.querySelector('#flexCheckDefault');

checkbox.addEventListener('change', (e) => {
  var isChecked = e.target.checked;
  myChart.setOption({
    series: [{
      id: 'chartLine',
      lineStyle: {
        color: isChecked ? 'red' : 'transparent'
      }
    }]
  })
});
body {
  padding: 50px 25px;
}
<script src="https://cdn.jsdelivr.net/npm/echarts@5.0.0/dist/echarts.min.js"></script>
<link href="https://getbootstrap.com/docs/5.0/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="form-check" style="margin-left: 100px;">
  <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" checked>
  <label class="form-check-label" for="flexCheckDefault">
    Activate & Deactivate line
  </label>
</div>
<div id="benchmark" style="min-height:500px;"></div>
Sergey Fedorov
  • 3,696
  • 2
  • 17
  • 21
1

Just update the chart instance with setOption({series: []}) or set transparent to line color. Wrap it into the function and call on button click. For action enable need to do the same steps in the opposite direction.

Sergey Fedorov
  • 3,696
  • 2
  • 17
  • 21