SVG Pie Chart Click Events

March 30, 2017 — Daniel Holmes

This is a simple little post to detail how to get mouse events like onClick to work correctly with a piechart or donut svg when you're using dashOffset to create the chart.

Here's an example SVG:

<svg width="10em" height="10em" viewBox="0 0 40 40">  
  <circle class="pieSegment segment1" cx="20" cy="20" r="15.915494309189533" fill="transparent" stroke="#1a0d1c" stroke-dashoffset="62.2" stroke-dasharray="24.599999999999998 75.4" stroke-width="5"></circle>
  <circle class="pieSegment segment2" cx="20" cy="20" r="15.915494309189533" fill="transparent" stroke="#335a68" stroke-dashoffset="37.3" stroke-dasharray="24.599999999999998 75.4" stroke-width="5"></circle>
  <circle class="pieSegment segment3" cx="20" cy="20" r="15.915494309189533" fill="transparent" stroke="#e9ad61" stroke-dashoffset="12.399999999999999" stroke-dasharray="24.599999999999998 75.4" stroke-width="5"></circle>
</svg>  

That looks like:

If you tired running an onClick for each of those circles, you'd likely find that the click events may fire on the incorrect circle. To fix that, it's a simple matter of adding pointer-events="stroke" or pointer-events="visibleStroke" to the circle elements to get the browser to correctly trigger the onClick events.

That's it!