java
java
// Render habits
function renderHabits() {
habitList.innerHTML = ''; // Clear habit list
li.innerHTML = `
<span>${habit.name}</span>
<div>
<button class="btn btn-complete" onclick="toggleComplete(${index})">$
{habit.completed ? 'Undo' : 'Complete'}</button>
<button class="btn btn-delete"
onclick="deleteHabit(${index})">Delete</button>
</div>
`;
habitList.appendChild(li);
});
updateHabitStats();
}
// Add habit
addHabitBtn.addEventListener('click', () => {
const habitName = habitInput.value.trim();
if (habitName) {
habits.push({ name: habitName, completed: false });
habitInput.value = ''; // Clear input field
updateLocalStorage();
renderHabits();
}
});
// Delete habit
function deleteHabit(index) {
habits.splice(index, 1);
updateLocalStorage();
renderHabits();
}
// Update localStorage
function updateLocalStorage() {
localStorage.setItem('habits', JSON.stringify(habits));
}
// Initial render
renderHabits();