Below is one working solution. In this version we separate the creation of the markup (which is returned as an HTML string by the function) from the “animation” step. Once the markup is inserted via innerHTML, we call another function that “animates” the bars by reading a custom attribute (the computed final height) and then gradually setting the height and revealing the value. (All CSS and HTML remain almost the same.)
Some points to note:
• We compute the final height for each bar (based on the random data and chart height) and store it in a data attribute (data‑final‑height) on each bar’s container.
• The returned HTML string contains the “bars” (with initial inline style height set to 0) and the labels. Once that HTML is inserted, the separate function animate_bars() selects each bar and, with a slight delay per bar, sets its height to the saved final value and adds a “visible” class (that, according to your CSS, will fade in the value).
• We wrap everything inside a DOMContentLoaded handler so that once the page is loaded the container is populated and then animated.
Below is the full HTML code. You can simply copy and run it (for example, by saving it in an HTML file), and you will see both the labels and the animated bars:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Weekly Bar Chart (Colored + Animated)</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: #f9fafb;
}
.chart-container {
width: 400px;
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
overflow: hidden;
}
.bar-chart {
display: flex;
justify-content: space-between;
align-items: flex-end;
height: 200px;
border-left: 2px solid #ccc;
border-bottom: 2px solid #ccc;
padding-top: 10px;
}
.bar-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
.bar {
width: 40px;
/* We start with 0 height; it will update after a delay */
height: 0;
border-radius: 4px 4px 0 0;
transition: height 0.8s ease-out, background-color 0.3s ease;
}
.red { background: #ff2222; }
.yellow { background: #facc15; }
.green { background: #34d399; }
.bar.red:hover { background: #bb2626; }
.bar.yellow:hover { background: #eab308; }
.bar.green:hover { background: #059669; }
.bar-value {
font-size: 12px;
margin-bottom: 4px;
color: #333;
opacity: 0;
transition: opacity 0.2s ease 0.2s;
}
.bar-value.visible { opacity: 1; }
.bar-labels {
display: flex;
justify-content: space-between;
margin-top: 8px;
}
.bar-label {
flex: 1;
text-align: center;
font-size: 14px;
color: #555;
}
</style>
</head>
<body>
<div class="chart-container">
<!-- The markup for the chart will be added here via innerHTML -->
</div>
<script>
// This function creates and returns the HTML string for the bar chart.
function get_bar_chart_html() {
const days = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"];
// Generate a random integer between min & max (inclusive)
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Build an array of random values between 80 and 90
const data = days.map(() => randInt(80, 90));
const maxVal = Math.max(...data);
const chartH = 200; // Height of the chart in pixels
let prevVal = null;
let barsHTML = "";
let labelsHTML = "";
data.forEach((val, i) => {
// Determine color based on the original logic:
// the first bar is "red", then if a bar is greater than previous it's red,
// equal is yellow, and lower is green.
const colour = i === 0 ? 'red' : (val > prevVal ? 'red' : (val === prevVal ? 'yellow' : 'green'));
prevVal = val;
// Calculate final height (in pixels) as a proportion of chartH
const finalHeight = (val / maxVal) * chartH;
// Each bar-item gets a data attribute holding its final height (so the animation can use it)
barsHTML += `
<div class="bar-item" data-final-height="${finalHeight}">
<span class="bar-value">${val}</span>
<div class="bar ${colour}" style="height: 0;"></div>
</div>
`;
labelsHTML += `<span class="bar-label">${days[i]}</span>`;
});
return `
<div class="bar-chart" id="barChart">
${barsHTML}
</div>
<div class="bar-labels">
${labelsHTML}
</div>
`;
}
// This function animates the bars once the markup is inserted.
function animate_bars() {
const chart = document.getElementById("barChart");
if (!chart) return;
const barItems = chart.querySelectorAll(".bar-item");
barItems.forEach((item, i) => {
const bar = item.querySelector(".bar");
const barValue = item.querySelector(".bar-value");
// Retrieve the final height (in px) from the custom data attribute
const finalHeight = item.getAttribute("data-final-height") + "px";
// Set a delay for each bar
setTimeout(() => {
bar.style.height = finalHeight;
barValue.classList.add("visible");
}, 50 * i + 50);
});
}
// When the document is loaded, insert the chart markup and then animate the bars.
document.addEventListener("DOMContentLoaded", () => {
const container = document.querySelector(".chart-container");
container.innerHTML = get_bar_chart_html();
animate_bars();
});
</script>
</body>
</html>
How It Works
-
Markup Generation:
The get_bar_chart_html() function generates the HTML string for the chart. Each bar-item includes:
- A
<span> with the value (initially invisible, per the CSS).
- A
<div> for the bar with an inline style of height: 0 so that it starts collapsed.
- A data attribute (
data-final-height) holding the computed final height in pixels.
-
Animation:
The animate_bars() function finds each bar and sets a delay (using setTimeout()) before updating the bar’s inline height style to the computed final height and adding the “visible” class to the value (thus starting the fade-in).
-
Initialization:
As soon as the DOM is fully loaded, the DOMContentLoaded event handler inserts the generated markup into the .chart-container and calls animate_bars().
This combined approach gives you both the markup (for innerHTML insertion) and the animations (bars growing and the values fading in) while ensuring labels are included. Let me know if you have any questions or need further modifications!