How to change cursor on hover of data labels in chart.js version 3?


I’ve been trying to change the mouse cursor to ‘pointer’ as soon as it is hovered on the data label.

I’m effectively able to achive this effect while hovering over data-points, so that is fine.

options: {
onHover: (eve, legendItems, chartElement) => {
      if (_.get(eve, 'native.target.style')) {
        eve.native.target.style.cursor = legendItems[0] ? 'pointer' : 'default';
      }
    }
}

I’m trying to follow this current documentation for the ChartDataLabels Plugin : https://chartjs-plugin-datalabels.netlify.app/guide/events.html#example

listeners: {
          click: ({ datasetIndex, dataIndex }) => {
            setTileActive(report.id);
            populateDrills(report.id, reportGroup, report.data.dataset[datasetIndex].values[dataIndex]);
            executeScroll();
            return;
          },
          enter: async (context) => {
            context.hovered = true;
            const chartTileElem = document.getElementById(`${report.id}-chart`);
            console.log('<><><><', chartTileElem.style.cursor, context);

            // _.set(context, 'chart.canvas.style.cursor', 'pointer');

            _.set(chartTileElem, 'style.cursor', 'pointer');

            // context.chart.canvas.style.cursor = 'pointer';
            return;
          },
          leave: (context) => {
            context.hovered = false;

            // const chartTileElem = document.getElementById(`${report.id}-chart`);
            // chartTileElem.style.cursor = 'default';

            // context.chart.canvas.style.cursor = 'default';
            return;
          },
          color: (context) => {
            return context.hovered ? 'green' : null;
          }
        }

This does re-render the chart but doesn’t change the cursor to pointer when needed. One weird behaviour I’ve found out is that it does change cursor to pointer in some of the bar-charts when the hovered item is of the highest value in that chart. Again, that happens rarely.

So please do suggest any solid solution that would change the cursor on hover of the data label.

EDIT-1: the suggested similar question: Chart.js how to show cursor pointer for labels & legends in line chart

differs a lot from this one. As it talks about the onHover behaviour on labels and legends, where as, in this thread I’m trying to find a solution for the data labels that gets rendered on top of the chart’s data points.

Source: CSS – Stack Overflow

November 21, 2021
Category : News
Tags: chart.js | charts | css | javascript | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.