DoeTheFourth
DoeTheFourth

Reputation: 405

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

I'm creating a line chart with chart.js. My x-axis is time-based and displays months.
Each "month column" should be clickable/selectable, but I cannot find a way to manage this. Methods like getElementAtEvent() return data, so I can find out which month is selected. But they only work if the user clicks right on a point, and not anywhere in the "column".

How can I do that? Or is there already a plugin for this?

Upvotes: 3

Views: 6407

Answers (1)

jordanwillis
jordanwillis

Reputation: 10705

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.

Upvotes: 5

Related Questions