-
Notifications
You must be signed in to change notification settings - Fork 0
/
scrtipt.js
51 lines (47 loc) · 1.28 KB
/
scrtipt.js
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
const form = document.getElementById('form');
const input = document.getElementById('input');
const todoList = document.getElementById('todos');
const todos = JSON.parse(localStorage.getItem('todos'));
if (todos) {
todos.forEach((todo) => addToDo(todo.text, todo.completed));
}
form.addEventListener('submit', (e) => {
e.preventDefault();
if (input.value.trim()) {
addToDo();
}
});
function addToDo(todo, completed) {
let inputText = input.value.trim();
if (todo) {
inputText = todo;
}
const newLi = document.createElement('li');
newLi.innerText = inputText;
if (completed) {
newLi.classList.add('completed');
}
todoList.appendChild(newLi);
input.value = '';
newLi.addEventListener('click', (event) => {
newLi.classList.toggle('completed');
updateLS();
});
newLi.addEventListener('contextmenu', (event) => {
event.preventDefault();
newLi.remove();
updateLS();
});
updateLS();
}
function updateLS() {
const listElements = todoList.querySelectorAll('li');
const todos = [];
listElements.forEach((element) =>
todos.push({
text: element.innerText,
completed: element.classList.contains('completed'),
})
);
localStorage.setItem('todos', JSON.stringify(todos));
}