-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
96 lines (82 loc) · 2.33 KB
/
main.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
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
86
87
88
89
90
91
92
93
94
95
96
let todoItems = [];
function renderTodo(todo) {
localStorage.setItem('todoItems', JSON.stringify(todoItems));
const list = document.querySelector('.js-todo-list');
const item = document.querySelector(`[data-key='${todo.id}']`);
if (todo.deleted) {
item.remove();
if (todoItems.length === 0) list.innerHTML = '';
return
}
const isChecked = todo.checked ? 'done': '';
const node = document.createElement("li");
node.setAttribute('class', `todo-item ${isChecked}`);
node.setAttribute('data-key', todo.id);
node.innerHTML = `
<input id="${todo.id}" type="checkbox"/>
<label for="${todo.id}" class="tick js-tick"></label>
<span>${todo.text}</span>
<button class="delete-todo js-delete-todo">
<svg><use href="#delete-icon"></use></svg>
</button>
`;
if (item) {
list.replaceChild(node, item);
} else {
list.append(node);
}
}
function addTodo(text) {
const todo = {
text,
checked: false,
id: Date.now(),
};
todoItems.push(todo);
renderTodo(todo);
}
function toggleDone(key) {
const index = todoItems.findIndex(item => item.id === Number(key));
todoItems[index].checked = !todoItems[index].checked;
renderTodo(todoItems[index]);
}
function deleteTodo(key) {
const index = todoItems.findIndex(item => item.id === Number(key));
const todo = {
deleted: true,
...todoItems[index]
};
todoItems = todoItems.filter(item => item.id !== Number(key));
renderTodo(todo);
}
const form = document.querySelector('.js-form');
form.addEventListener('submit', event => {
event.preventDefault();
const input = document.querySelector('.js-todo-input');
const text = input.value.trim();
if (text !== '') {
addTodo(text);
input.value = '';
input.focus();
}
});
const list = document.querySelector('.js-todo-list');
list.addEventListener('click', event => {
if (event.target.classList.contains('js-tick')) {
const itemKey = event.target.parentElement.dataset.key;
toggleDone(itemKey);
}
if (event.target.classList.contains('js-delete-todo')) {
const itemKey = event.target.parentElement.dataset.key;
deleteTodo(itemKey);
}
});
document.addEventListener('DOMContentLoaded', () => {
const ref = localStorage.getItem('todoItems');
if (ref) {
todoItems = JSON.parse(ref);
todoItems.forEach(t => {
renderTodo(t);
});
}
});