-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
88 lines (72 loc) · 2.44 KB
/
script.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
'use strict'
class Todo {
constructor(form, input, todoList, todoComleted, todoButtons){
this.form = document.querySelector(form);
this.input = document.querySelector(input);
this.todoList = document.querySelector(todoList);
this.todoComleted = document.querySelector(todoComleted);
this.todoData = JSON.parse(localStorage.getItem('toDoList')) || {};
}
addToStorage(){
localStorage.setItem('toDoList', JSON.stringify(this.todoData));
}
render(){
this.todoList.textContent = '';
this.todoComleted.textContent = '';
Object.entries(this.todoData).forEach(this.createItem);
this.addToStorage();
}
createItem = ([key, {value, completed}]) => {
const li = document.createElement('li');
li.classList.add('todo-item');
li.insertAdjacentHTML('beforeend', `
<span class="text-todo">${value}</span>
<div class="todo-buttons">
<button class="todo-remove"></button>
<button class="todo-complete"></button>
</div>
`);
if(completed){
this.todoComleted.append(li)
} else {
this.todoList.append(li);
}
li.addEventListener('click', (event) => {
let target = event.target;
if(target.matches('.todo-remove')){
this.deleteItem(key);
} else if(target.matches('.todo-complete')){
this.completedItem(key);
}
});
}
addTodo(event){
event.preventDefault();
if(this.input.value.trim()){
this.todoData[this.generateKey()] = {
value: this.input.value,
completed: false
};
this.input.value = '';
this.render();
}
}
generateKey(){
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
deleteItem(key){
delete this.todoData[key]
this.render();
}
completedItem(k){
const currentItem = this.todoData[k];
this.todoData[k] = { ...currentItem, completed: !currentItem.completed}
this.render();
}
init(){
this.form.addEventListener('submit', this.addTodo.bind(this));
this.render();
}
}
const todo = new Todo('.todo-control', '.header-input', '.todo-list', '.todo-completed');
todo.init();