Project: Expense Tracker App
Build a fully functional personal finance Expense Tracker using vanilla JavaScript — with add/delete expenses, category filtering, running totals, and data persistence via localStorage. No frameworks needed.
Project Overview
The Expense Tracker is a classic beginner-to-intermediate JavaScript project that brings together virtually every core concept you've learned in this course — DOM manipulation, events, arrays, objects, localStorage, and modular code organisation.
By the end you will have a fully working mini-app that lets users log income and expense entries, see a live balance summary, filter by category, and have everything automatically saved so data survives a page refresh.
Features We'll Build
Here is the complete feature set of the app. Each feature maps to specific JavaScript concepts you've covered in earlier chapters.
Concepts used in this project:
Project Folder Structure
Keep things simple — three files in one folder is all you need for this project:
Step 1 — HTML Structure
Start with index.html. We need three main areas: a
summary bar (balance, income, expenses), an
add-transaction form, and a transaction list with a filter
bar.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Expense Tracker</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<h1 class="app-title">💰 Expense Tracker</h1>
<!-- Summary Cards -->
<div class="summary-grid">
<div class="summary-card balance">
<span class="card-label">Balance</span>
<span class="card-value" id="totalBalance">₹0.00</span>
</div>
<div class="summary-card income">
<span class="card-label">Income</span>
<span class="card-value" id="totalIncome">₹0.00</span>
</div>
<div class="summary-card expense">
<span class="card-label">Expenses</span>
<span class="card-value" id="totalExpense">₹0.00</span>
</div>
</div>
<!-- Add Transaction Form -->
<form class="add-form" id="addForm">
<h3>Add Transaction</h3>
<input type="text" id="txName" placeholder="Description (e.g. Grocery)" />
<input type="number" id="txAmount" placeholder="Amount (negative = expense)" />
<select id="txCategory">
<option value="salary">💼 Salary</option>
<option value="food">🍔 Food</option>
<option value="rent">🏠 Rent</option>
<option value="transport">🚌 Transport</option>
<option value="health">💊 Health</option>
<option value="shopping">🛍️ Shopping</option>
<option value="other">📦 Other</option>
</select>
<p class="error-msg" id="formError"></p>
<button type="submit">Add Transaction</button>
</form>
<!-- Filter + Transaction List -->
<section class="list-section">
<div class="list-header">
<h3>Transactions</h3>
<select id="filterCategory">
<option value="all">All Categories</option>
<option value="salary">💼 Salary</option>
<option value="food">🍔 Food</option>
<option value="rent">🏠 Rent</option>
<option value="transport">🚌 Transport</option>
<option value="health">💊 Health</option>
<option value="shopping">🛍️ Shopping</option>
<option value="other">📦 Other</option>
</select>
</div>
<ul class="tx-list" id="txList"></ul>
</section>
</div>
<script src="app.js"></script>
</body>
</html>
-500 means money going out. Positive numbers are income.
This is a simple convention that eliminates a separate "type" toggle.
Step 2 — CSS Styling
Open style.css and paste in the styles. We use CSS
custom properties (variables) for colors so the design is easy to customise. The key visual
idea is green = income, red = expense.
/* ── CSS Variables ─────────────────────────────── */
:root {
--bg: #0f172a;
--card-bg: #1e293b;
--border: rgba(255,255,255,0.08);
--text: #f1f5f9;
--text-muted: #94a3b8;
--green: #22c55e;
--red: #ef4444;
--accent: #f7df1e;
--radius: 12px;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Segoe UI', sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
padding: 32px 16px;
}
.container {
max-width: 560px;
margin: 0 auto;
}
/* ── Title ──────────────────────────────────────── */
.app-title {
font-size: 26px;
font-weight: 700;
margin-bottom: 24px;
color: var(--accent);
}
/* ── Summary Cards ──────────────────────────────── */
.summary-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
margin-bottom: 24px;
}
.summary-card {
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 16px;
display: flex;
flex-direction: column;
gap: 6px;
}
.card-label {
font-size: 12px;
text-transform: uppercase;
letter-spacing: .6px;
color: var(--text-muted);
}
.card-value {
font-size: 20px;
font-weight: 700;
}
.summary-card.balance .card-value { color: var(--accent); }
.summary-card.income .card-value { color: var(--green); }
.summary-card.expense .card-value { color: var(--red); }
/* ── Form ───────────────────────────────────────── */
.add-form {
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 20px;
display: flex;
flex-direction: column;
gap: 12px;
margin-bottom: 24px;
}
.add-form h3 { font-size: 16px; font-weight: 600; }
.add-form input,
.add-form select {
background: rgba(255,255,255,0.05);
border: 1px solid var(--border);
border-radius: 8px;
padding: 10px 14px;
color: var(--text);
font-size: 14px;
outline: none;
transition: border-color .2s;
}
.add-form input:focus,
.add-form select:focus {
border-color: rgba(247,223,30,0.5);
}
.add-form button {
background: var(--accent);
color: #1a1a14;
border: none;
border-radius: 8px;
padding: 11px;
font-weight: 700;
font-size: 14px;
cursor: pointer;
transition: filter .2s;
}
.add-form button:hover { filter: brightness(1.1); }
.error-msg {
color: var(--red);
font-size: 13px;
min-height: 16px;
}
/* ── Transaction List ───────────────────────────── */
.list-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 14px;
}
.list-header h3 { font-size: 16px; font-weight: 600; }
#filterCategory {
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: 8px;
padding: 6px 10px;
color: var(--text);
font-size: 13px;
cursor: pointer;
}
.tx-list { list-style: none; display: flex; flex-direction: column; gap: 8px; }
.tx-item {
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: 10px;
padding: 12px 14px;
display: flex;
align-items: center;
gap: 10px;
border-left: 3px solid transparent;
transition: border-color .2s;
}
.tx-item.income-item { border-left-color: var(--green); }
.tx-item.expense-item { border-left-color: var(--red); }
.tx-info { flex: 1; }
.tx-name { font-size: 14px; font-weight: 500; }
.tx-category { font-size: 12px; color: var(--text-muted); margin-top: 2px; }
.tx-amount {
font-weight: 700;
font-size: 15px;
}
.tx-amount.positive { color: var(--green); }
.tx-amount.negative { color: var(--red); }
.tx-delete {
background: none;
border: none;
cursor: pointer;
color: var(--text-muted);
font-size: 18px;
padding: 2px 6px;
border-radius: 4px;
transition: color .2s, background .2s;
}
.tx-delete:hover {
color: var(--red);
background: rgba(239,68,68,0.1);
}
.empty-state {
text-align: center;
color: var(--text-muted);
font-size: 14px;
padding: 32px;
}
Step 3 — JavaScript Logic
Now the heart of the project — app.js. We'll break the
logic into focused functions, each with a single responsibility. This is called the
Single Responsibility Principle (SRP) — a key software design rule.
/* ── 1. STATE ─────────────────────────────────────────────── */
const STORAGE_KEY = 'et_transactions';
function loadTransactions() {
try {
return JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];
} catch {
return [];
}
}
function saveTransactions(data) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
}
let transactions = loadTransactions();
/* ── 2. DOM REFERENCES ────────────────────────────────────── */
const txList = document.getElementById('txList');
const addForm = document.getElementById('addForm');
const txName = document.getElementById('txName');
const txAmount = document.getElementById('txAmount');
const txCategory = document.getElementById('txCategory');
const formError = document.getElementById('formError');
const filterSelect = document.getElementById('filterCategory');
const balanceEl = document.getElementById('totalBalance');
const incomeEl = document.getElementById('totalIncome');
const expenseEl = document.getElementById('totalExpense');
/* ── 3. RENDER TRANSACTIONS ───────────────────────────────── */
function renderTransactions(filterVal = 'all') {
const filtered = filterVal === 'all'
? transactions
: transactions.filter(t => t.category === filterVal);
if (filtered.length === 0) {
txList.innerHTML = `<li class="empty-state">No transactions yet. Add one above! 💸</li>`;
return;
}
txList.innerHTML = filtered.map(t => {
const isIncome = t.amount >= 0;
const amtClass = isIncome ? 'positive' : 'negative';
const itemClass = isIncome ? 'income-item' : 'expense-item';
const sign = isIncome ? '+' : '';
return `
<li class="tx-item ${itemClass}" data-id="${t.id}">
<div class="tx-info">
<div class="tx-name">${t.name}</div>
<div class="tx-category">${t.category}</div>
</div>
<span class="tx-amount ${amtClass}">${sign}₹${Math.abs(t.amount).toFixed(2)}</span>
<button class="tx-delete" data-id="${t.id}" title="Delete">✕</button>
</li>
`;
}).join('');
}
/* ── 4. UPDATE SUMMARY CARDS ──────────────────────────────── */
function updateSummary() {
const income = transactions
.filter(t => t.amount > 0)
.reduce((sum, t) => sum + t.amount, 0);
const expense = transactions
.filter(t => t.amount < 0)
.reduce((sum, t) => sum + t.amount, 0);
const balance = income + expense;
balanceEl.textContent = `₹${balance.toFixed(2)}`;
incomeEl.textContent = `₹${income.toFixed(2)}`;
expenseEl.textContent = `₹${Math.abs(expense).toFixed(2)}`;
}
/* ── 5. ADD TRANSACTION ───────────────────────────────────── */
addForm.addEventListener('submit', e => {
e.preventDefault();
formError.textContent = '';
const name = txName.value.trim();
const amount = parseFloat(txAmount.value);
const cat = txCategory.value;
// Validation
if (!name) {
formError.textContent = 'Please enter a description.';
return;
}
if (isNaN(amount) || amount === 0) {
formError.textContent = 'Enter a valid non-zero amount.';
return;
}
const newTx = {
id: crypto.randomUUID(),
name,
amount,
category: cat,
date: new Date().toLocaleDateString()
};
transactions.push(newTx);
saveTransactions(transactions);
renderTransactions(filterSelect.value);
updateSummary();
txName.value = txAmount.value = '';
txName.focus();
});
/* ── 6. DELETE (event delegation) ────────────────────────── */
txList.addEventListener('click', e => {
const btn = e.target.closest('.tx-delete');
if (!btn) return;
const id = btn.dataset.id;
transactions = transactions.filter(t => t.id !== id);
saveTransactions(transactions);
renderTransactions(filterSelect.value);
updateSummary();
});
/* ── 7. FILTER ────────────────────────────────────────────── */
filterSelect.addEventListener('change', () => {
renderTransactions(filterSelect.value);
});
/* ── 8. INIT ──────────────────────────────────────────────── */
renderTransactions();
updateSummary();
How It All Connects
Let's map each piece of the app to the JavaScript concept powering it:
| App Feature | JS Concept Used | Chapter Reference |
|---|---|---|
| Store & load data | localStorage + JSON.parse/stringify | Ch 57 — localStorage |
| Add transaction | Array.push + form events | Ch 30 – Arrays, Ch 43 – Events |
| Delete transaction | Array.filter + event delegation | Ch 32 – map/filter, Ch 44 – Delegation |
| Filter by category | Array.filter on category property | Ch 32 – Array iteration |
| Balance totals | Array.reduce() | Ch 32 – reduce |
| Render list | innerHTML + template literals + map | Ch 42 – DOM manipulation |
| Unique IDs | crypto.randomUUID() | Web APIs (built-in browser) |
| Form validation | Conditional checks + error display | Ch 45 – Forms & Validation |
Transaction Categories
The app supports 7 categories, each colour-coded in the UI. You can easily add more by
extending the <select> options in both the form
and filter elements.
new Date() comparisons. Or add a
Chart.js pie chart to visualise spending per category.
Common Mistakes to Avoid
saveTransactions(transactions) after
every push or filter. Forgetting this means data is lost on reload.
parseFloat() and always check with
isNaN() — empty input parses to
NaN which will break your totals silently.
crypto.randomUUID() or
Date.now() for unique IDs. Hardcoded IDs will
conflict when you add multiple items.
Try It Yourself
The live editor below contains a working single-file version of the Expense Tracker. All HTML, CSS, and JS are combined. Edit it and see the result live in the preview panel.
localStorage version from the code above for data
persistence.
Which method is the best way to handle click events on a dynamically generated list of delete buttons?
- The Expense Tracker project combines DOM manipulation, arrays, objects, events, and localStorage in a real-world context.
- Separate HTML, CSS, and JS into three files — this is professional practice and keeps code maintainable.
-
Event delegation on the parent
<ul>handles all delete button clicks without attaching listeners to every item. - Array.reduce() efficiently calculates balance, income, and expense totals from the transactions array.
-
Always call
saveTransactions()after every mutation andJSON.parse/stringifyfor localStorage read/write. -
Use
crypto.randomUUID()for unique, collision-free transaction IDs. - Possible extensions: date filtering, Chart.js category pie chart, edit-in-place, CSV export, multi-currency support.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.