-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
92 lines (80 loc) · 2.36 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
89
90
91
92
let todo = JSON.parse(localStorage.getItem("todo")) || [];
const todoInput = document.getElementById("todoInput");
const todoList = document.querySelector(".todoList");
const todoCount = document.getElementById("todoCount");
const addButton = document.querySelector(".btn");
const deleteButton = document.getElementById("deleteBtn");
document.addEventListener("DOMContentLoaded", function () {
addButton.addEventListener("click", addTask);
todoInput.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
event.preventDefault();
addTask();
}
});
deleteButton.addEventListener("click", deleteAllTasks);
displayTasks();
});
function addTask() {
const newTask = todoInput.value.trim();
if (newTask !== "") {
todo.push({
text: newTask,
disabled: false,
});
saveToLocalStorage();
todoInput.value = "";
displayTasks();
}
}
function saveToLocalStorage() {
localStorage.setItem("todo", JSON.stringify(todo));
}
function deleteAllTasks() {
todo = [];
saveToLocalStorage()
displayTasks()
}
function displayTasks() {
todoList.innerHTML = "";
todo.forEach((item, index) => {
const p = document.createElement("p");
p.innerHTML = `
<div class="todo-container">
<input type="checkbox" class="todo-checkbox" id="input-${index}" ${
item.disabled ? "checked" : ""
}>
<p id="todo-${index}" class="${
item.disabled ? "disabled" : ""
}" onclick="editTask(${index})">${item.text}</p>
</div>
`;
p.querySelector(".todo-checkbox").addEventListener("change", () =>
toggleTask(index)
);
todoList.appendChild(p);
});
todoCount.textContent = todo.length;
}
function toggleTask(index) {
todo[index].disabled = !todo[index].disabled
saveToLocalStorage()
displayTasks()
}
function editTask(index){
const todoItem = document.getElementById(`todo-${index}`)
const existingText = todo[index].text
const inputElement = document.createElement("input")
inputElement.value = existingText
todoItem.replaceWith(inputElement)
inputElement.focus()
inputElement.addEventListener("blur", function() {
const updatedText = inputElement.value.trim();
if(updatedText)
{
todo[index].text = updatedText
saveToLocalStorage()
}
displayTasks()
})
}