kitchen800
kitchen800

Reputation: 227

On click event to show name of pie chart slice in chartsJS

I am using chartsjs. I want to click on a pie chart slice and set an alert to show the name of the slice that was clicked on.

responsive: false,
onClick : (event, items) =>{
    alert("Clicked");
}

this will produce thew term ‘clicked’ on any slice. But how do I just get the slice. When I change the term “clicked” for items the result is [object Object]. How do I isolate the name of the slice. You know the name that appears when you hover your mouse over a chartsjs pie chart slice.

when I inspect the chart section I click on (taking the first pie section for example) I see :

 [i]
0: i
hidden: false
_chart: ni {id: 2, ctx: CanvasRenderingContext2D, canvas: canvas#myChart4, config: {…}, width: 650, …}
_datasetIndex: 0
_index: 0
_model:
backgroundColor: "rgb(0, 72, 165)"
borderAlign: "center"
borderColor: "#fff"
borderWidth: 2
circumference: 1.3057964574823102
endAngle: -0.26499986931258634
innerRadius: 78.4
label: false
outerRadius: 156.8
startAngle: -1.5707963267948966
x: 325
y: 192.2
[[Prototype]]: Object

Upvotes: 1

Views: 1496

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31371

As you said you get an object, if you log this object you see it is an array containing all active elements. If you log the element itself you see it contains the datasetIndex and the dataIndex, with these you can get the current label from the chart like so:

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    onClick: (evt, activeEls, chart) => {
      console.log(chart.data.labels[activeEls[0].index])
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>

Edit

It seems like you are using V2, process is basicly the same but chart variable is defined at different place:

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    onClick: (evt, activeEls) => {
      console.log(activeEls[0]._chart.data.labels[activeEls[0]._index])
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

Upvotes: 1

Related Questions