-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
85 lines (76 loc) · 2.55 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
// Retrieve todo from local storage or initialize an empty array
let todo = JSON.parse(localStorage.getItem("todo")) || [];
const todoInput = document.getElementById("todo-input");
const todoList = document.getElementById("todo-list");
const todoCount = document.getElementById("todo-count");
const addButton = document.querySelector(".btn");
const deleteButton = document.getElementById("delete-btn");
// Initialize
document.addEventListener("DOMContentLoaded", function () {
addButton.addEventListener("click", addTask);
todoInput.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
event.preventDefault(); // Prevents default Enter key behavior
addTask();
}
});
deleteButton.addEventListener("click", deleteAllTasks);
displayTasks();
});
function addTask() {
const newTask = todoInput.value.trim();
if (newTask !== "") {
todo.unshift({ text: newTask, disabled: false });
saveToLocalStorage();
todoInput.value = "";
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 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();
});
}
function toggleTask(index) {
todo[index].disabled = !todo[index].disabled;
saveToLocalStorage();
displayTasks();
}
function deleteAllTasks() {
todo = [];
saveToLocalStorage();
displayTasks();
}
function saveToLocalStorage() {
localStorage.setItem("todo", JSON.stringify(todo));
}