[Chartjs]-Chart.JS – Polar area – Legend hover style and margin

4πŸ‘

βœ…

You can achieve the desired behavior using a combination of the legend onHover config option (to change the pointer style to pointer) and the custom tooltips config option (to change the pointer style back to default).

Here is an example config demonstrating a working solution. I wasn’t sure if you were using jQuery or not so I decided not to use it. Feel free to change accordingly.

options: {
  legend: {
    position: 'top',
    labels: {
      fontColor: 'rgb(255, 99, 132)'
    },
    onHover: function(event, legendItem) {
      document.getElementById("canvas").style.cursor = 'pointer';
    }
  },
  tooltips: {
    custom: function(tooltip) {
      if (!tooltip.opacity) {
        document.getElementById("canvas").style.cursor = 'default';
        return;
      }
    }
  }
}

4πŸ‘

I found a different way to make this work. This lines up more literally in my mind. Perhaps the framework was updated in the interim since this was initially answered.

 // This event fires anytime you mouse over the chart canvas.
onHover: function (event) {
    event.target.style.cursor = 'default';
},
responsive: true,
maintainAspectRatio: false,
legend: {
    display: true,
    position: 'bottom',
    onHover: function (event, legendItem) {
        // There is only a legendItem when your mouse is positioned over one
        if (legendItem) {
            event.target.style.cursor = 'pointer';
        }
    }
}

In case anyone wants to know more, here are the docs for events and the legend.

1πŸ‘

Faster, without scanning the DOM every time, you find the target under native in the hover event

Tested in version 3.2.1 and 3.3.2 (latest on 2021 jun 22)

options: {
  plugins : {
    legend: {   
      labels: {
        onHover: function (e) {
          e.native.target.style.cursor = 'pointer';
        },
        onLeave: function (e) {
          e.native.target.style.cursor = 'default';
        }
      }
    }
  }
}

0πŸ‘

The accepted answer did not work for me because my tooltips are always visible (position: "nearest"). So I use a timeout to change and revert the cursor style:

onHover: function(event, legendItem) {
    document.getElementById("canvas").style.cursor = "pointer";
    clearTimeout(hoverTimeout); // global var
    hoverTimeout = setTimeout(function() {
        document.getElementById("canvas").style.cursor = "default";
    }, 100);
}

It’s a dirty trick but it works.

Leave a comment