Chartjs-Dynamic Changing of Chart Type (Bar to Line as Example) in in Chart.js with PHP and MySQL

0👍

To do that, of course, you have to add event listeners to run some code when you click on a dropdown item. In your event handlers, a safe strategy with Chart.js is to destroy the chart and immediately create another one with a new configuration object. Here is an example:

function config(type) {
  return {
    type,
    data: {
      labels: ['Category 1', 'Category 2', 'Category 3'],
      datasets: [{
        label: 'Dataset',
        data: [10, 20, 15]
      }]
    }
  }
}

function init(type) {
  return new Chart(document.getElementById('myChart'), config(type));
}

let chart = init('bar');

document.querySelector('#bar').addEventListener('click', () => {
  chart.destroy();
  chart = init('bar');
});

document.querySelector('#line').addEventListener('click', () => {
  chart.destroy();
  chart = init('line');
});
@import "https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css";

.chart-container {
  position: relative;
  height: 90vh;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/js/bootstrap.bundle.min.js" integrity="sha512-i9cEfJwUwViEPFKdC1enz4ZRGBj8YQo6QByFTF92YXHi7waCqyexvRD75S5NVTsSiTv7rKWqG9Y5eFxmRsOn0A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div class="container">
  <div class="row">
    <div class="col">
      <div class="dropdown">
        <button class="btn btn-primary dropdown-toggle mt-3 mb-3" type="button" data-bs-toggle="dropdown" aria-expanded="false">
          Dropdown button
        </button>
        <ul class="dropdown-menu">
          <li><button id="bar" class="dropdown-item" type="button">Bar</button></li>
          <li><button id="line" class="dropdown-item" type="button">Line</button></li>
        </ul>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col">
      <div class="chart-container">
        <canvas id="myChart"></canvas>
      </div>  
    </div>
  </div>
</div>

Leave a comment