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?
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?
Share Improve this question asked Mar 27, 2017 at 12:43 DoeTheFourthDoeTheFourth 4051 gold badge4 silver badges14 bronze badges1 Answer
Reset to default 5I 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.