How can I add multiple charts without repeating javascript code?

Viewed 894
<HTML>
<HEAD>
<script>
function createChart(divId, data) {
  var myChart = echarts.init(document.getElementById(divId));

  option = {
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: data,
      type: 'bar'
    }]
  };

  myChart.setOption(option);
}

createChart('main1', [10,20,30,40,50,60,70]);
createChart('main2', [15,25,35,45,55,65,75]);
</script>
</HEAD>
<BODY>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js"></script>

<div id="main1" style="width:100%;height:400px;"></div>
<div id="main2" style="width:100%;height:400px;"></div>
</BODY>
</HTML>

It shows blank elemnts! It shows this errors in Console: ReferenceError: echarts is not defined The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.

1 Answers

You can definitely do that by creating a configurable function. For now, i have configured two properties div ID and data. You can make other properties configurable and passed to this common function.

Please find below the working code:

function createChart(divId, data) {
  var myChart = echarts.init(document.getElementById(divId));

  option = {
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: data,
      type: 'bar'
    }]
  };

  myChart.setOption(option);
}

createChart('main', [10,20,30,40,50,60,70]);
createChart('main-2', [15,25,35,45,55,65,75]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js"></script>

<div id="main" style="width: 600px;height:400px;"></div>

<div id="main-2" style="width: 600px;height:400px;"></div>

UPDATE

This is the updated code, the javascript part should be at the bottom of the body tag. And i have changed uppercase tags to lowercase as per standard

<html>
<head>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js"></script>

<div id="main1" style="width:100%;height:400px;"></div>
<div id="main2" style="width:100%;height:400px;"></div>

<script>
function createChart(divId, data) {
  var myChart = echarts.init(document.getElementById(divId));

  option = {
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: data,
      type: 'bar'
    }]
  };

  myChart.setOption(option);
}

createChart('main1', [10,20,30,40,50,60,70]);
createChart('main2', [15,25,35,45,55,65,75]);
</script>

</body>
</html>
Related