0% found this document useful (0 votes)
2 views

java

Uploaded by

Binay Tamang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

java

Uploaded by

Binay Tamang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

// DOM elements

const habitInput = document.getElementById('habit-input');


const addHabitBtn = document.getElementById('add-habit-btn');
const habitList = document.getElementById('habit-list');

// Initialize habit data


let habits = JSON.parse(localStorage.getItem('habits')) || [];

// Setup chart.js for habit stats


const ctx = document.getElementById('habit-progress-chart').getContext('2d');
const habitChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Habits'],
datasets: [{
label: 'Completed Habits',
data: [0],
backgroundColor: 'rgba(0, 198, 255, 0.6)',
borderRadius: 8,
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
ticks: { color: '#fff' },
grid: { color: '#444' }
},
y: {
ticks: { color: '#fff' },
grid: { color: '#444' },
max: 10,
min: 0
}
}
}
});

// Render habits
function renderHabits() {
habitList.innerHTML = ''; // Clear habit list

habits.forEach((habit, index) => {


const li = document.createElement('li');
li.classList.toggle('completed', habit.completed);

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();
}
});

// Toggle habit completion


function toggleComplete(index) {
habits[index].completed = !habits[index].completed;
updateLocalStorage();
renderHabits();
}

// Delete habit
function deleteHabit(index) {
habits.splice(index, 1);
updateLocalStorage();
renderHabits();
}

// Update localStorage
function updateLocalStorage() {
localStorage.setItem('habits', JSON.stringify(habits));
}

// Update chart with completed habits


function updateHabitStats() {
const completedHabits = habits.filter(habit => habit.completed).length;
habitChart.data.datasets[0].data = [completedHabits];
habitChart.update();
}

// Initial render
renderHabits();

You might also like