-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
90 lines (80 loc) · 2.26 KB
/
Copy pathscript.js
File metadata and controls
90 lines (80 loc) · 2.26 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
86
87
88
89
90
//All the elements....
const input = document.getElementById("todo-input");
const addBtn = document.getElementById("add-btn");
const list = document.getElementById("todo-list");
// try to load local storage 1st
const saved = localStorage.getItem("todos"); //chatgpt this line to understand better
const todos = saved ? JSON.parse(saved) : [];
function saveTodos() {
//storage todos in local storage....
localStorage.setItem("todos", JSON.stringify(todos));
}
//create a dom node and append todo here
function createTodoNode(todo, index) {
const li = document.createElement("li");
//checkbox
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = !!todo.completed;
checkbox.addEventListener("change", () => {
todo.completed = checkbox.checked;
//TODO: visual feed back ; stricking the lines
textSpan.style.textDecoration = todo.completed ? "line-through" : "";
saveTodos();
});
//text to todo
const textSpan = document.createElement("span");
textSpan.textContent = todo.text;
textSpan.style.margin = "4px 8px";
if (todo.completed) {
textSpan.style.textDecoration = "line-through";
}
//Double click to editg
textSpan.addEventListener("dblclick", () => {
const newText = prompt("Edit todo", todo.text);
if (newText !== "") {
todo.text = newText.trim();
textSpan.textContent = todo.text;
saveTodos();
}
});
//Delete todo
const delBtn = document.createElement("button");
delBtn.textContent = "Delete";
delBtn.addEventListener("click", () => {
todos.splice(index, 1);
render();
saveTodos();
});
li.appendChild(checkbox);
li.appendChild(textSpan);
li.appendChild(delBtn);
return li;
}
//render all todo list here
function render() {
list.innerHTML = "";
todos.forEach((todo, index) => {
const node = createTodoNode(todo, index);
createTodoNode(todo, index);
list.appendChild(node);
});
}
function addTodo() {
const text = input.value.trim();
if (!text) {
return;
}
//push the todo object
todos.push({ text, completed: false });
input.value = "";
render();
saveTodos();
}
addBtn.addEventListener("click", addTodo);
input.addEventListener("keydown", (e) => {
if (e.key == "Enter") {
addTodo();
}
});
render();