2

I'm working with chart.js v2 and I am trying simulate the hover state of a segment on a doughnut graph when the chart loads so it appears there is a section alright highlighted.

I've been searching and combing the code for a day now and can't figure out a good way to do this.

Thanks in advance!

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

nice find, i wish they documented any of this
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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.