-
Notifications
You must be signed in to change notification settings - Fork 15
/
Habit tracker with progress tracker
62 lines (56 loc) · 2.25 KB
/
Habit tracker with progress tracker
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Habit Tracker</title>
<style>
.completed { color: green; }
</style>
</head>
<body>
<h2>Track a New Habit</h2>
<form id="habitForm">
<input type="text" id="habitName" placeholder="Habit Name" required>
<input type="number" id="goal" placeholder="Daily Goal (in minutes, pages, etc.)" required>
<button type="submit">Start Tracking</button>
</form>
<div id="habitList">
<!-- Tracked habits will be listed here -->
</div>
<script>
let habits = JSON.parse(localStorage.getItem('habits')) || [];
document.getElementById('habitForm').addEventListener('submit', function(e) {
e.preventDefault();
const habitName = document.getElementById('habitName').value.trim();
const goal = parseInt(document.getElementById('goal').value, 10);
habits.push({ habitName, goal, progress: 0 });
localStorage.setItem('habits', JSON.stringify(habits));
displayHabits();
this.reset();
});
function updateProgress(index) {
habits[index].progress++;
localStorage.setItem('habits', JSON.stringify(habits));
displayHabits();
}
function displayHabits() {
const list = document.getElementById('habitList');
list.innerHTML = ''; // Clear the list
habits.forEach((habit, index) => {
const habitDiv = document.createElement('div');
habitDiv.innerHTML = `<div>Habit: ${habit.habitName}, Goal: ${habit.goal}, Progress: ${habit.progress}</div>`;
const progressButton = document.createElement('button');
progressButton.textContent = 'Mark Progress';
progressButton.addEventListener('click', () => updateProgress(index));
habitDiv.appendChild(progressButton);
if (habit.progress >= habit.goal) {
habitDiv.classList.add('completed');
habitDiv.innerHTML += ` <span>Goal Reached!</span>`;
}
list.appendChild(habitDiv);
});
}
displayHabits();
</script>
</body>
</html>