Make months on x-axis clickable on chart.js line chart - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Make months on x-axis clickable on chart.js line chart

Demo Code

ResultView the demo in separate window

<html lang="en">
   <head> 
      <title>Chart.js - Get X-Axis Region on Click - Time Scale</title> 
   </head> 
   <body translate="no"> 
      <div style="width:40%;"> 
         <canvas id="canvas"></canvas> 
      </div> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script> 
      <script>
      window.chartColors = {//from   ww  w .j ava 2s. c o  m
  red: 'rgb(255, 99, 132)',
  orange: 'rgb(255, 159, 64)',
  yellow: 'rgb(255, 205, 86)',
  green: 'rgb(75, 192, 192)',
  blue: 'rgb(54, 162, 235)',
  purple: 'rgb(153, 102, 255)',
  grey: 'rgb(231,233,237)'
};
var line1 = [
  {x: '2017-04-15', y: 10},
  {x: '2017-09-15', y: 10},
];
var config = {
  type: 'line',
  data: {
    datasets: [{
      label: "My First dataset",
      backgroundColor: window.chartColors.red,
      borderColor: window.chartColors.red,
      data: line1,
    }]
  },
  options: {
    responsive: true,
    onClick: function(e) {
      var xLabel = this.scales['x-axis-0'].getValueForPixel(e.x);
      console.log(xLabel.format('MMM YYYY'));
      console.log("clicked x-axis area: " + xLabel.format('MMM YYYY'));
    },
    title: {
      display:true,
      text:'Chart.js - Get X-Axis Region on Click'
    },
    tooltips: {
      mode: 'index',
      intersect: false,
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          unit: 'month',
        }
      }]
    }
  }
};
var ctx = document.getElementById("canvas").getContext("2d");
var myLine = new Chart(ctx, config);
      </script>  
   </body>
</html>

Related Tutorials