Open In App

How to Create a Click Event on Pie Chart ?

Last Updated : 03 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Chart.js is an open-source free JavaScript library that is used to visualize data-informed charts like pie, lines, bars, scatter, and many more. Chart.js provides an onClick event feature by using it you can interact with specific segments of the pie chart. In this article, we will learn about how to create an onClick event in a pie chart.

Approach

Chart.js provides you with a built-in onClick event handler that you can configure when initializing the chart. This onClick event handler will take a call back function so when you perform any click event you can define custom actions. This onClick event handler function is defined inside an options object of the chart.

CDN link:

 <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

Syntax:

let chart = new Chart(canvas_element, {
type: 'chart_type', // ex: line, bar, pie
data: { labels[...], datasets[{..}, {..}]},
options: {
// The onClick Event
onClick: function (event, elements) {
// Actions to be performed
}
}
});

Parameters:

  • event Parameter: It is an object that represents the click event and it contains values such as event type (it would be always click), DOM Element, clientX, and clientY value, etc.
  • element Parameter: It is an array that contains information about the chart elements such as data points, segments that were clicked, x & y coordinates, animations, etc.

Example: In this example, we are implementing the on-click event on the pie chart.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,
                                      initial-scale=1.0">
    <title>Pie Chart Example</title>
    <!-- Include Chart.js library -->
    <script src=
    </script>
    <style>
        div {
            height: 50vh;
            width: 50vw;
        }
    </style>
</head>
 
<body>
    <h1>GeeksForGeeks | Pie Chart</h1>
    <div>
        <!-- Create a canvas element to render the chart -->
        <canvas id="pieChart" width="400" height="400">
        </canvas>
    </div>
 
    <script>
        // Get the 2D rendering context of the canvas
        let ctx = document.getElementById('pieChart')
            .getContext('2d');
        let dataValue = {
            // Labels for each segment of the pie
            labels: ['JavaScript',
                'Python',
                'Java',
                'C++',
                'PHP'],
            // Datasets for the chart
            datasets: [{
                data: [40, 35, 25, 17, 18],
                // Data points for each segment
                backgroundColor: ['rgba(255, 99, 132, 0.8)',
                    'rgba(75, 192, 192, 0.8)',
                    'rgba(54, 162, 235, 0.8)',
                    'rgba(255, 205, 86, 0.8)',
                    'rgba(153, 102, 255, 0.8)'],
                borderWidth: 2 // Border width for each segment
            }]
        }
        // Create a new Pie Chart
        let pieChart = new Chart(ctx, {
            // Specify the chart type
            type: 'pie',
            // Provide data for the chart
            data: dataValue,
            // Additional options for the chart
            options: {
                responsive: true, // It make the chart responsive
                // This plugin will display Title of chart
                plugins: {
                    title: {
                        display: true,
                        text: 'Number of Students Enrolled Course'
                    }
                },
                // Event handler for a click on a chart element
                onClick: function (event, elements) {
                    const clickedElement = elements[0];
                    const datasetIndex = clickedElement.index;
                    const label = dataValue.labels[datasetIndex];
                    const labelValue = dataValue.datasets[0].data[datasetIndex];
 
                    // Show an alert with information about the clicked segment
                    alert(`Clicked on: ${label} and it's value is ${labelValue}`);
                }
            }
        });
    </script>
</body>
 
</html>


Output:

pieechart



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads