The Prerequisites
Creating the Expense Chart
HTML5 and CSS
The first container with the balance and SVG should be within a "div" element, which can be styled with Flexbox.
<div class="balance">
<div class="bal-section">
<h2>My balance</h2>
<p class="monthly-balance">$921.48</p>
</div>
<div class="svg">
<i class="uil uil-adjust-circle"></i>
</div>
</div>
.balance {
display: flex;
flex-direction: row;
justify-content: space-around;
background-color: var(--primary-color);
width: 450px;
height: 100px;
border: none;
border-radius: 20px;
box-sizing: border-box;
margin-top: 20px;
}
The second container will reference the chart along with the monthly total. The "canvas" element is a container for the expense chart, which will be created via JavaScript.
<div class="chart-div">
<h1>Spending - Last 7 days</h1>
<div class="js-chart">
<canvas id="myChart" style="width:100%;max-width:700px"></canvas>
</div>
<hr />
<div class="bottom-data">
<div class="left">
<h3>Total this month</h3>
<p class="monthly-total">$478.33</p>
</div>
<div class="right">
<h4>+2.4%</h4>
<p class="per">from last month</p>
</div>
</div>
</div>
JavaScript
You should create three variables for the labels, data, and the background colors for each of the bars. These variable will be used in the expense chart object.
const weekday = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
const expenseValue = [17.45, 34.91, 52.36, 37.07, 23.79, 43.28, 25.48];
const barColors = ["#f4ceb8", "#e2cbd9", "#c2a2c2", "#bfd1d0", "#e9a7b8", "#a4d4dc", "#dfefc6"];
By using the "new" keyword, you can create an instance of the "chart" object. You must reference the "id" from the "canvas" element to acquire the chart, which will allow you to add all the values to the properties.
new Chart("myChart", {
type: "bar",
data: {
labels: weekday,
datasets: [{
backgroundColor: barColors,
data: expenseValue
}]
},
options: {
scales: {
x: {
grid: {
display: false
}
},
y: {
grid: {
display: false
}
}
},
plugins: {
legend: {display: false}
}}
});
I hope you enjoyed this tutorial!
Top comments (3)
Rock on, Puja!
Thanks for sharing this one.
Just to note, I think it's pretty helpful to include the code in code blocks rather than just pictures of the code. That way folks can more easily copy it over and run it, adapt it, etc.
Don't get me wrong, it's up to you! It's totally cool if you just wanna snap screenshots of the code, but I would recommend sharing it in code blocks.
Regardless though, thanks for sharing!
Thank you so much for the feedback @michaeltharrington! I went ahead and added my code in code blocks!
Woot woot! Awesome, Puja. Really appreciate you doing so. 🙌