[Chartjs]-Make months on x-axis clickable on chart.js line chart

5๐Ÿ‘

โœ…

I was able to get this working using an undocumented time scale prototype method called .getValueForPixel(), which returns the scale value of the scale region that was clicked.

This method returns a moment object that was used to generate the scale tick label, so you can use the same format string configured for your time scale when displaying this value (if you want them to be visually equal). I coupled this with the generic onClick option config property for a pretty simple approach for what you are wanting to do.

Here is how to do it. In your options object, add an onClick property using this function.

onClick: function(e) {
  var xLabel = this.scales['x-axis-0'].getValueForPixel(e.x);
  console.log(xLabel.format('MMM YYYY'));
  alert("clicked x-axis area: " + xLabel.format('MMM YYYY'));
},

Here is a codepen example to see it in action.

Leave a comment