Open In App

How to Fix "Bar Chart Showing Old Data when Hovering" in ChartJS?

Last Updated : 25 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

ChartJS is a popular open-source JavaScript library for creating a variety of charts, including lines, bars, pies, and more. It's used for its simplicity, flexibility, and responsiveness. We are going to discuss how can we fix the Chart Showing Old Data when Hovering in ChartJS.

Problem Explanation

When working with dynamic data or animations in ChartJS, we might face an issue where old data appears while hovering over a chart. In this tutorial, we will focus on the steps of how to fix the "Bar Chart showing old data when hovering" in ChartJS.

Prerequisites

Approach

  • Set up the basic HTML and CSS structure.
  • Include the Chart.js CDN and the data labels plugin using <script> tags.
  • Then add a <canvas> element to your HTML file where the chart will be rendered.
  • Create a new Chart object with the desired chart type (e.g., line bar).
  • Then write JavaScript to initialize a Chart object with real-time dynamic data.
  • Here we create a helper function named generateRandomData() to produce random numbers for the chart. And we can see those each time when we hover over the chart.

Example: This example shows the implementation to fix the bar chart showing old

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>Dynamic Bar Chart Example</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f4f4f4;
            font-family: 'Arial', sans-serif;
        }

        h1 {
            font-size: 2rem;
            margin-bottom: 0.5rem;
            color: #333;
            text-align: center;
        }

        p {
            font-size: 1rem;
            color: #555;
            text-align: center;
            max-width: 700px;
            margin-bottom: 2rem;
            padding: 0 1rem;
        }

        #chart-container {
            width: 60%;
            max-width: 800px;
            height: 400px;
            background-color: white;
            padding: 1rem;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            border-radius: 10px;
        }
    </style>
</head>

<body>

    <h1>Bar Chart showing old data when hovering</h1>

    <div id="chart-container">
        <canvas id="myChart"></canvas>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        const ctx = document.getElementById('myChart').getContext('2d');

        // Function to generate random data
        function generateRandomData() {
            return Array.from({ length: 5 }, () => Math
                .floor(Math.random() * 100));
        }

        // Initial data for the bar chart
        let data = {
            labels: ['A', 'B', 'C', 'D', 'E'],
            datasets: [{
                label: 'Dynamic Data',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                borderColor: 'rgba(75, 192, 192, 1)',
                borderWidth: 1,
                data: generateRandomData(),
                // Random initial data
            }]
        };

        // Configuration for the bar chart
        const config = {
            type: 'bar',
            data: data,
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                },
                onHover: function (event, chartElement) {
                    if (chartElement.length > 0) {
                        // Update the data with random values when hovering
                        data.datasets[0].data = generateRandomData();
                        myChart.update();
                        // Update the chart to reflect new data
                    }
                }
            }
        };

        // Create the bar chart
        const myChart = new Chart(ctx, config);
    </script>

</body>

</html>

Output:


Next Article

Similar Reads