TheUnreal
TheUnreal

Reputation: 24472

Chart.js - custom css to dataset on mouse hover

I have the following code in my pie chart options in order to change the mouse cursor to pointer on hover:

hover: {
      onHover: (e, el) => {
        const section = el[0];
        const currentStyle = e.target.style;
        currentStyle.cursor = section ? 'pointer' : 'normal';
      }
    }

Problems

  1. the cursor changes to pointer even when its pointed outside pie (or inside). I want it to change only when hovering a dataset. Is it possible?

  2. the hover method is executing even when the cursor stay inside the element and can cause performance issue, is it possible to use the same function with onmouseenter on chart.js?

Thanks

enter image description here

Upvotes: 2

Views: 1087

Answers (2)

dfsq
dfsq

Reputation: 193261

You only problem is that you used unvalid value for cursor, there is no "normal", it should be "default".

Try this:

hover: {
  onHover: (e, el) => {
    const section = el[0];
    const currentStyle = e.target.style;
    currentStyle.cursor = section ? 'pointer' : 'default'; // <-- default here
  }
}

To limit number of times useful functionality of onHover methods is triggered you can do simple check for previous target:

onHover: (() => {
  let prevTarget;

  return (e, el) => {
    const section = el[0];

    if (prevTarget !== section) {
      // Code in this if-block is called only when necessary

      const currentStyle = e.target.style;
      currentStyle.cursor = section ? 'pointer' : 'default';

      // .........
    }

    prevTarget = section;
  }
})()

Upvotes: 1

Noel Schenk
Noel Schenk

Reputation: 726

Just add CSS styles to the pie datasets.

cursor: pointer;

With this method you don't even need Javascript to set the cursor property.

Upvotes: 0

Related Questions