Change chart.js options based on window width - Javascript Chart.js

Javascript examples for Chart.js:Chart Configuration

Description

Change chart.js options based on window width

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> 
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//  w ww  . java  2  s . co  m

var toggleXAxesDisplayPlugin = {
  resize: function(chartInstance, newChartSize) {
    if (chartInstance.config.options.hideXAxesWhenChartIsXXS) {
      if (newChartSize.width < 480) {
        chartInstance.config.options.scales.xAxes.forEach(function(axis) {
          axis.display = false;
        });
      } else {
        chartInstance.config.options.scales.xAxes.forEach(function(axis) {
          axis.display = true;
        });
      }
    }
  }
};
Chart.pluginService.register(toggleXAxesDisplayPlugin);
var allTimeAll = $("#my-chart");
var allTimeAllChart = new Chart(allTimeAll, {
  type: 'bar',
  data: {
    labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
    datasets: [{
      label: 'Confirmed',
      data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
      backgroundColor: [
        'red',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)',
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'green',
        'rgba(255, 159, 64, 1)',
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1,
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        gridLines: {
          display: true
        },
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        display: true,
        gridLines: {
          display: false
        },
      }]
    },
    hideXAxesWhenChartIsXXS: true
  }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="my-chart" width="400" height="400"></canvas>  
   </body>
</html>

Related Tutorials