-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
69 lines (62 loc) · 2.11 KB
/
script.js
File metadata and controls
69 lines (62 loc) · 2.11 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
const inputBox = document.getElementById("input-box");
const listContainer = document.getElementById("list-container");
let tasks = [];
inputBox.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
const task = inputBox.value.trim();
if (task) {
const newTask = {
text: task,
completed: false
};
tasks.push(newTask);
renderTaskList();
inputBox.value = ''; // Clear the input field
}
}
});
listContainer.addEventListener("click", function(e) {
if (e.target.className === "done") {
const taskIndex = Array.prototype.indexOf.call(e.target.parentNode.parentNode.children, e.target.parentNode);
tasks[taskIndex].completed = !tasks[taskIndex].completed;
renderTaskList();
} else if (e.target.className === "remove") {
const taskIndex = Array.prototype.indexOf.call(e.target.parentNode.parentNode.children, e.target.parentNode);
tasks.splice(taskIndex, 1);
renderTaskList();
}
}, false);
function renderTaskList() {
listContainer.innerHTML = '';
tasks.forEach((task) => {
const taskList = document.querySelector('ul');
const newTask = document.createElement('li');
const doneButton = document.createElement('span');
doneButton.className = 'done';
doneButton.innerHTML = '✔';
newTask.appendChild(doneButton);
const taskText = document.createTextNode(task.text);
newTask.appendChild(taskText);
const removeButton = document.createElement('span');
removeButton.className = 'remove';
removeButton.innerHTML = '✖';
newTask.appendChild(removeButton);
if (task.completed) {
newTask.classList.add("completed");
}
taskList.appendChild(newTask);
});
}
function saveData() {
localStorage.setItem("tasks", JSON.stringify(tasks));
}
function loadTasks() {
const storedTasks = localStorage.getItem("tasks");
if (storedTasks) {
tasks = JSON.parse(storedTasks);
renderTaskList();
}
}
loadTasks();
// Add event listener to save data when user closes the tab
window.addEventListener("beforeunload", saveData);