/
todoList.js
85 lines (75 loc) · 2.16 KB
/
todoList.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
const toDoForm = document.querySelector(".js-toDoForm"),
toDoInput = toDoForm.querySelector("input"),
toDoList = document.querySelector(".js-toDoList");
const TODO_LS = "toDos",
TODO_CNT = "toDoCount";
let saveList = [],
checkBox = new Image();
function saveToDos() {
// 스트링으로 변환 후 저장
localStorage.setItem(TODO_LS, JSON.stringify(saveList));
}
function deleteToDo(event) {
const btn = event.target;
let li = btn.parentNode;
if (btn.localName === "img") li = li.parentNode;
setTimeout(function() {
// 체크박스의 애니메이션 구현을 위해 시간지연 시킴
toDoList.removeChild(li);
const cleanTodo = saveList.filter(function(toDo) {
return toDo.id !== parseInt(li.id);
});
saveList = cleanTodo;
saveToDos();
}, 300);
}
function writeToDo(text) {
const li = document.createElement("li");
const delBtn = document.createElement("div");
const span = document.createElement("div");
const newId = saveList.length + 1;
delBtn.innerHTML =
"<img src='images/todo/checkBox-0.png' width=30px height=30px/>";
// delBtn 클릭 -> toDo 항목 삭제
delBtn.addEventListener("mousedown", function() {
delBtn.innerHTML =
"<img src='images/todo/checkBox-1.png' width=30px height=30px/>";
});
delBtn.addEventListener("mouseup", deleteToDo);
span.innerText = `${text}`;
// li요소 생성 후에 추가해주는 과정
li.appendChild(delBtn);
li.appendChild(span);
li.id = newId;
toDoList.appendChild(li);
const toDoObj = {
text: text,
id: newId
};
saveList.push(toDoObj);
saveToDos();
}
function handleSubmit(event) {
event.preventDefault();
const currentValue = toDoInput.value;
if (saveList.length < 3) {
if (currentValue != "") {
writeToDo(currentValue);
}
} else alert("three list!");
toDoInput.value = "";
}
function loadTodoList() {
const loadedToDos = localStorage.getItem(TODO_LS);
if (loadedToDos !== null) {
const parseToDos = JSON.parse(loadedToDos);
parseToDos.forEach(function(toDo) {
writeToDo(toDo.text);
});
}
}
function init() {
loadTodoList();
toDoForm.addEventListener("submit", handleSubmit);
}
init();