const cpuDiv = document.createElement('div');
let cpuBarColor = 'green'; // Default color
if (health.metrics.cpu_usage > 75) {
cpuBarColor = 'red';
} else if (health.metrics.cpu_usage > 50) {
cpuBarColor = 'yellow';
}
cpuDiv.innerHTML = `
<div class="flex justify-between mb-1">
<span class="text-sm">CPU Usage</span>
<span class="text-sm">${health.metrics.cpu_usage}%</span>
</div>
<div class="w-full bg-darkest rounded-full h-2">
<div class="bg-${cpuBarColor} h-2 rounded-full" style="width: ${health.metrics.cpu_usage}%"></div>
</div>
`;
healthContainer.appendChild(cpuDiv);
Key improvements and explanations:
How to use with Tailwind CSS (recommended):
-
Make sure Tailwind is set up in your project. Follow the official Tailwind documentation for installation and configuration: https://tailwindcss.com/docs/installation
-
Define your color palette (if needed). Tailwind comes with a default color palette, but you might want to customize it. Edit your tailwind.config.js file:
module.exports = {
theme: {
extend: {
colors: {
'custom-green': '#28a745', // Example green
'custom-yellow': '#ffc107', // Example yellow
'custom-red': '#dc3545', // Example red
},
},
},
}
-
Use the Tailwind color classes: Modify the JavaScript to use the Tailwind color classes:
const cpuDiv = document.createElement('div');
let cpuBarColor = 'custom-green'; // Default color
if (health.metrics.cpu_usage > 75) {
cpuBarColor = 'custom-red';
} else if (health.metrics.cpu_usage > 50) {
cpuBarColor = 'custom-yellow';
}
cpuDiv.innerHTML = `
<div class="flex justify-between mb-1">
<span class="text-sm">CPU Usage</span>
<span class="text-sm">${health.metrics.cpu_usage}%</span>
</div>
<div class="w-full bg-darkest rounded-full h-2">
<div class="bg-${cpuBarColor} h-2 rounded-full" style="width: ${health.metrics.cpu_usage}%"></div>
</div>
`;
healthContainer.appendChild(cpuDiv);
If you're not using Tailwind CSS:
Remove the bg- prefix from the color classes and use inline styles:
const cpuDiv = document.createElement('div');
let cpuBarColor = 'green'; // Default color
if (health.metrics.cpu_usage > 75) {
cpuBarColor = 'red';
} else if (health.metrics.cpu_usage > 50) {
cpuBarColor = 'yellow';
}
cpuDiv.innerHTML = `
<div class="flex justify-between mb-1">
<span class="text-sm">CPU Usage</span>
<span class="text-sm">${health.metrics.cpu_usage}%</span>
</div>
<div class="w-full bg-darkest rounded-full h-2">
<div class="h-2 rounded-full" style="width: ${health.metrics.cpu_usage}%; background-color: ${cpuBarColor};"></div>
</div>
`;
healthContainer.appendChild(cpuDiv);
This version directly sets the background-color style attribute. This is less maintainable than using CSS classes, but it works if you don't have a CSS framework.
Remember to adjust the thresholds (50 and 75) and colors to match your specific requirements. The Tailwind approach is generally preferred for larger projects because it promotes consistency and maintainability.