<!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>