Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
97 lines (83 loc) · 2.97 KB
/
Copy pathscript.js
File metadata and controls
97 lines (83 loc) · 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const balanceEl = document.getElementById('balance');
const transactionList = document.getElementById('transaction-list');
const descriptionEl = document.getElementById('description');
const amountEl = document.getElementById('amount');
const categoryEl = document.getElementById('category');
const addTransactionBtn = document.getElementById('add-transaction');
const chartCanvas = document.getElementById('expense-chart');
let transactions = JSON.parse(localStorage.getItem('transactions')) || [];
// Update LocalStorage
function updateLocalStorage() {
localStorage.setItem('transactions', JSON.stringify(transactions));
}
// Update the chart
let chart;
function updateChart() {
const expenseCategories = ['food', 'transport', 'shopping', 'others'];
const categoryTotals = expenseCategories.map(category =>
transactions
.filter(transaction => transaction.category === category)
.reduce((sum, t) => sum + Math.abs(t.amount), 0)
);
if (chart) chart.destroy();
chart = new Chart(chartCanvas, {
type: 'pie',
data: {
labels: expenseCategories,
datasets: [
{
data: categoryTotals,
backgroundColor: ['#ff6384', '#36a2eb', '#ffcd56', '#4bc0c0'],
},
],
},
options: {
responsive: true,
},
});
}
// Update balance and list
function updateUI() {
const balance = transactions.reduce((acc, transaction) => acc + transaction.amount, 0);
balanceEl.textContent = `$${balance.toFixed(2)}`;
transactionList.innerHTML = '';
transactions.forEach((transaction, index) => {
const transactionEl = document.createElement('li');
transactionEl.classList.add(transaction.amount > 0 ? 'income' : 'expense');
transactionEl.innerHTML = `
${transaction.description} <span>${transaction.amount > 0 ? '+' : ''}$${transaction.amount.toFixed(2)}</span>
<button class="delete-btn" onclick="deleteTransaction(${index})">X</button>
`;
transactionList.appendChild(transactionEl);
});
updateChart();
}
// Add new transaction
function addTransaction() {
const description = descriptionEl.value.trim();
const amount = parseFloat(amountEl.value.trim());
const category = categoryEl.value;
if (!description || isNaN(amount)) {
alert('Please fill out all fields.');
return;
}
const newTransaction = {
description,
amount,
category,
};
transactions.push(newTransaction);
updateLocalStorage();
updateUI();
descriptionEl.value = '';
amountEl.value = '';
}
// Delete transaction
function deleteTransaction(index) {
transactions.splice(index, 1);
updateLocalStorage();
updateUI();
}
// Initialize app
addTransactionBtn.addEventListener('click', addTransaction);
updateUI();