Chartjs-Rendering multiple chart.js charts in one page when scroll to the section

0👍

You can use the deferred plugin for this:

Chart.register(ChartDeferred);

const data = {
  labels: ['one', 'two', 'three', 'four'],
  datasets: [{
    label: '% of Respondents',
    data: [55, 51, 46, 36],
    backgroundColor: [
      'rgba(79, 38, 131, 0.8)',
      'rgba(79, 38, 131, 0.6)',
      'rgba(79, 38, 131, 0.4)',
      'rgba(79, 38, 131, 0.2)'
    ]
  }]
};

const data2 = {
  labels: ['one', 'two', 'three', 'four'],
  datasets: [{
    label: '% of Respondents',
    data: [55, 51, 46, 36],
    backgroundColor: [
      'rgba(79, 38, 131, 0.8)',
      'rgba(79, 38, 131, 0.6)',
      'rgba(79, 38, 131, 0.4)',
      'rgba(79, 38, 131, 0.2)'
    ]
  }]
};

// config for myChart
const config = {
  type: 'bar',
  data,
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    },
    indexAxis: 'y'
  }
};

// render myChart
const myChart = new Chart(
  document.getElementById('myChart'),
  config
);

// config for myChart2
const config2 = {
  type: 'bar',
  data: data2,
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    },
    indexAxis: 'y'
  }
};

// render myChart2
const myChart2 = new Chart(
  document.getElementById('myChart2'),
  config2
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-deferred@2.0.0 "></script>
<div class="blankDiv" style="height: 700px;width: 100%;">
  Scroll Down to See the chart
</div>
<div style="max-width: 70em;">
  <canvas id="myChart"></canvas>
</div>
<div class="blankDiv" style="height: 700px;width: 100%;">
  Scroll Down to See the chart
</div>
<div style="max-width: 70em;">
  <canvas id="myChart2"></canvas>
</div>

Leave a comment