Modern Todo App - Vanilla JS (PasteText Demo)
Modern Todo App - Vanilla JS (PasteText Demo)
===========================================
// Modern Todo App - Vanilla JS (Copy for your projects!)
class TodoApp {
constructor() {
this.todos = JSON.parse(localStorage.getItem('todos')) || [];
this.init();
}
init() {
this.render();
document.querySelector('#add-todo').addEventListener('submit', e => {
e.preventDefault();
this.addTodo(document.querySelector('#todo-input').value);
});
}
addTodo(text) {
this.todos.push({ id: Date.now(), text, completed: false });
localStorage.setItem('todos', JSON.stringify(this.todos));
this.render();
}
render() {
const list = document.querySelector('#todo-list');
list.innerHTML = this.todos.map(todo => `
<li class="${todo.completed ? 'completed' : ''}">
<input type="checkbox" ${todo.completed ? 'checked' : ''} onchange="todoApp.toggle(${todo.id})">
<span>${todo.text}</span>
<button onclick="todoApp.delete(${todo.id})">Delete</button>
</li>
`).join('');
}
toggle(id) {
const todo = this.todos.find(t => t.id === id);
todo.completed = !todo.completed;
localStorage.setItem('todos', JSON.stringify(this.todos));
this.render();
}
delete(id) {
this.todos = this.todos.filter(t => t.id !== id);
localStorage.setItem('todos', JSON.stringify(this.todos));
this.render();
}
}
const todoApp = new TodoApp();
Featured
Advertisement
Category
Action