Open In App

How to Handle onClick Events on ChartJS Bar Charts in Chart.JS?

Last Updated : 26 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Chart.js, we can add behavior to bar charts by handling onClick events. This allows developers to create interactive charts where specific actions are triggered when a user clicks on a particular bar. Such actions can range from displaying additional information to dynamically updating the chart data, providing a more engaging user experience.

 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>

These are the following approaches to handle onClick Events on ChartJS Bar:

Basic onClick Event

In this approach, we perform a basic onClick event on a Chart.js bar chart. When a user clicks on any bar, the event captures the clicked bar's label and value and then displays them in an alert box.

Example: The below example performs a Basic onClick Event on ChartJS Bar Charts in ChartJS.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Handle onClick Event</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }

        h1 {
            color: green;
            text-align: center;
        }

        h3 {
            margin-top: 0;
            text-align: center;
        }

        .chart-container {
            position: relative;
            width: 300px;
            height: 500px;
            margin: auto;
        }
    </style>
</head>

<body>
    <h3>Basic onClick Event</h3>
    <div class="chart-container">
        <canvas id="chart1"></canvas>
    </div>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js">
    </script>
    <script>
        const ctx1 = document.getElementById('chart1').getContext('2d');
        const chart1 = new Chart(ctx1, {
            type: 'bar',
            data: {
                labels: ['HTML', 'CSS', 'JavaScript', 'Python'],
                datasets: [{
                    label: 'GeeksforGeeks Tutorials',
                    data: [30, 50, 70, 40],
                    backgroundColor: ['red', 'blue', 'green', 'purple']
                }]
            },
            options: {
                responsive: true,
                onClick: (e) => {
                    const activePoints = chart1.getElementsAtEventForMode(e, 'nearest', {
                        intersect: true
                    }, false);
                    if (activePoints.length > 0) {
                        const index = activePoints[0].index;
                        const label = chart1.data.labels[index];
                        const value = chart1.data.datasets[0].data[index];
                        alert(`Label: ${label}\nValue: ${value}`);
                    }
                }
            }
        });
    </script>
</body>

</html>

Output:

Advanced onClick Event with Data Manipulation

In this approach, we are implementing an advanced onClick event on a Chart.js bar chart that allows for data manipulation. When a user clicks on a bar, the value associated with the clicked bar is increased by 10, and the chart is dynamically updated to reflect the change.

Example: The below example performs Advanced onClick Event with Data Manipulation on ChartJS Bar Charts in Chart.JS.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Handle onClick event</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }

        h3 {
            margin-top: 0;
            text-align: center;
        }

        .chart-container {
            position: relative;
            width: 300px;
            height: 300px;
            margin: auto;
        }
    </style>
</head>

<body>
    <h3>Advanced onClick Event</h3>
    <div class="chart-container">
        <canvas id="chart2"></canvas>
    </div>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js">
    </script>
    <script>
        const ctx2 = document.getElementById('chart2').getContext('2d');
        const chart2 = new Chart(ctx2, {
            type: 'bar',
            data: {
                labels: ['Beginner', 'Intermediate', 'Advanced'],
                datasets: [{
                    label: 'GeeksforGeeks Skill Levels',
                    data: [20, 40, 60],
                    backgroundColor: ['orange', 'yellow', 'blue']
                }]
            },
            options: {
                responsive: true,
                onClick: (e) => {
                    const activePoints =
                        chart2.getElementsAtEventForMode(e, 'nearest', {
                            intersect: true
                        }, false);
                    if (activePoints.length > 0) {
                        const index = activePoints[0].index;
                        chart2.data.datasets[0].data[index] += 10;
                        chart2.update();
                    }
                }
            }
        });
    </script>
</body>

</html>

Output:


Similar Reads