最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make months on x-axis clickable on chart.js line chart - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论