Chartjs-How can my Chart.js custom interaction mode use 'nearest' functionality?

2👍

I don’t understand weel the use case but I think it could be something like that:

Interaction.modes.myCustomMode = function(chart, e, options, useFinalPosition) {
  const nearestItems = Interaction.modes.nearest(chart, e, {axis: 'x', intersect: false}, useFinalPosition);
  
  const items = [];
  for (const element of nearestItems) {
      const index = element.index;
    if (index_tracker != index) {
        index_tracker = index;
        items.push(element);
        const xLabel = chart.data.labels[index];
        const yValue1 = chart.data.datasets[0].data[index];
        const yValue2 = chart.data.datasets[1].data[index];
        chart.options.plugins.annotation.annotations.box.xMin = index - 0.5;
        chart.options.plugins.annotation.annotations.box.xMax = index + 0.5;
        chart.update();    
    }
  };
  return items;
};

Codepen: https://codepen.io/stockinail/pen/yLRBQwK

EDIT: add info

The official documentation about the custom interaction is here: https://www.chartjs.org/docs/latest/configuration/interactions.html#custom-interaction-modes

But I think you have already had a look on that, seeing your code.
Unfortunately the doc doesn’t explain well that the "default" modes are stored in the map where you are adding new one. Maybe an improvement could be done.
Anyway there is a discussion in GH where a similar topic is touched: https://github.com/chartjs/Chart.js/discussions/11148
If I may, also how you are managing the annotations options could be improved going to scriptable options. If you can share the whole chart options, I could suggest some updates to you.

Leave a comment