[Chartjs]-Chart.js set active segment on initialize

5👍

Setting a segment’s hover style is a bit confusing because its not really documented anywhere. Nevertheless, I was able to figure it out a while back when I wanted to highlight a segment when it’s legend label was hovered.

To do this, you need to use the pie chart .updateHoverStyle() prototype method and pass in the segment you want highlighted. The chart segments are stored in the _meta object in an array where each segment index matches the position of each value in your chart’s data array.

Here is an example (assuming your chart instance is stored in a var called myPie.

// get the segment we want to highlight
var activeSegment = myPie.data.datasets[0]._meta[0].data[segmentIndexToHihlight];

// update the hover style
myPie.updateHoverStyle([activeSegment], null, true);

// render so we can see it
myPie.render(); 

You just need to define what segment you want to highlight and store it in a var called segmentIndexToHihlight and it should work.

Here is a codepen example demonstrating this. Note, I purposely did not highlight the segment on load (I wait 3 seconds) so that you can see the change occur.

0👍

I found another way to preselect a segment, basically you can simulate a click event on the point. You can find in the dataset model the position x and y. Here you can find my solution:

function simulateClick(x, y) {
  const clickEvent = document.createEvent('MouseEvents');
  clickEvent.initMouseEvent('click', true, true, window, 0, 0, 0, x, y, 
  false, false, false, false, 0, null);
  document.elementFromPoint(x, y).dispatchEvent(clickEvent);
}

function initActivePoint(index) {
  const activePoint = myChart.data.datasets[0]._meta[0].data[index];
  simulateClick(activePoint._model.x, activePoint._model.y);
}

initActivePoint(0);

Leave a comment