-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
85 lines (72 loc) · 2.71 KB
/
script.js
File metadata and controls
85 lines (72 loc) · 2.71 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
document.addEventListener('DOMContentLoaded', function() {
const todoInput = document.getElementById('todo-input');
const addBtn = document.getElementById('add-btn');
const todoList = document.getElementById('todo-list');
let todos = JSON.parse(localStorage.getItem('todos')) || [];
// Render todos from localStorage
renderTodos();
// Add new todo
addBtn.addEventListener('click', addTodo);
todoInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') addTodo();
});
function addTodo() {
const text = todoInput.value.trim();
if (text) {
const newTodo = {
id: Date.now(),
text: text,
completed: false
};
todos.push(newTodo);
saveAndRender();
todoInput.value = '';
}
}
function renderTodos() {
todoList.innerHTML = '';
todos.forEach(todo => {
const todoItem = document.createElement('li');
todoItem.className = 'todo-item';
todoItem.dataset.id = todo.id;
const todoText = document.createElement('span');
todoText.className = 'todo-text';
todoText.textContent = todo.text;
if (todo.completed) {
todoText.style.textDecoration = 'line-through';
todoText.style.color = '#888';
}
const actionsDiv = document.createElement('div');
actionsDiv.className = 'todo-actions';
const editBtn = document.createElement('button');
editBtn.className = 'edit-btn';
editBtn.textContent = 'Edit';
editBtn.addEventListener('click', () => editTodo(todo.id));
const deleteBtn = document.createElement('button');
deleteBtn.className = 'delete-btn';
deleteBtn.textContent = 'Delete';
deleteBtn.addEventListener('click', () => deleteTodo(todo.id));
actionsDiv.appendChild(editBtn);
actionsDiv.appendChild(deleteBtn);
todoItem.appendChild(todoText);
todoItem.appendChild(actionsDiv);
todoList.appendChild(todoItem);
});
}
function editTodo(id) {
const todo = todos.find(todo => todo.id === id);
const newText = prompt('Edit your todo:', todo.text);
if (newText !== null && newText.trim() !== '') {
todo.text = newText.trim();
saveAndRender();
}
}
function deleteTodo(id) {
todos = todos.filter(todo => todo.id !== id);
saveAndRender();
}
function saveAndRender() {
localStorage.setItem('todos', JSON.stringify(todos));
renderTodos();
}
});