<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Bar Chart Race</title>
</head>
<style>
.chart-container {
position: relative;
width: 100%;
height: 200px; /* Adjust based on the number of bars */
}
.bar {
position: absolute;
height: 40px;
margin: 5px 0;
background-color: steelblue;
display: flex;
align-items: center;
padding-left: 10px;
color: white;
width: 0; /* Start with 0 width */
transition: width 1.5s ease-in-out, transform 1.5s ease-in-out; /* Smooth width and position transition */
}
.time-indicator {
font-size: 24px;
text-align: center;
margin-top: 20px;
}
</style>
<body>
<div class=”chart-container”>
<div class=”bar” data-country=”Mexico”>Mexico</div>
<div class=”bar” data-country=”United States”>United States</div>
<div class=”bar” data-country=”France”>France</div>
</div>
<div class=”time-indicator”></div>
</body>
<script>
const data = [
{ year: 1995, values: { ‘Mexico’: 20, ‘United States’: 30, ‘France’: 15 } },
{ year: 2000, values: { ‘Mexico’: 40, ‘United States’: 20, ‘France’: 25 } },
{ year: 2005, values: { ‘Mexico’: 60, ‘United States’: 70, ‘France’: 55 } },
{ year: 2010, values: { ‘Mexico’: 10, ‘United States’: 90, ‘France’: 75 } },
{ year: 2020, values: { ‘Mexico’: 100, ‘United States’: 100, ‘France’: 95 } }
];
let currentYearIndex = 0;
const barsContainer = document.querySelector(‘.chart-container’);
const timeIndicator = document.querySelector(‘.time-indicator’);
function updateChart() {
// Update time indicator
timeIndicator.textContent = data[currentYearIndex].year;
// Get the current year’s data and convert it to an array of entries
const yearData = Object.entries(data[currentYearIndex].values);
// Sort the bars based on values (highest first)
const sortedBarsData = yearData.sort((a, b) => b[1] – a[1]);
// Update each bar’s width, text content, and position based on the sorted data
sortedBarsData.forEach(([country, value], index) => {
const bar = document.querySelector(`.bar[data-country=’${country}’]`);
// Update the width based on the new value (for the growing effect)
bar.style.width = value + ‘%’;
bar.textContent = `${country} ${value} billion`;
// Move the bar to its new position using transform (y-axis movement)
bar.style.transform = `translateY(${index * 50}px)`; // Adjust this value based on bar height + margin
});
currentYearIndex++;
if (currentYearIndex >= data.length) {
clearInterval(animationInterval); // Stop the animation at the end of the data
}
}
// Start the animation at intervals
const animationInterval = setInterval(updateChart, 2000);
// Initial render
updateChart();
</script>
</html>