-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
93 lines (77 loc) · 2.31 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
93
"use strict";
let addTaskButton = document.querySelector('#add-task-button');
let removeButtons = document.querySelectorAll('.delete-btn');
let listTask = document.querySelector('#task-list');
let inputTask = document.querySelector('#input-task');
let toDoList = [
// .. tasks objects
];
function loadLocalStorage() {
//We will use local storage to store the tasks. The localStorage property allows saving key/value pairs right in a web browser.
if (localStorage.getItem("tasks")) {
toDoList = JSON.parse(localStorage.getItem("tasks")) || [];
showTasks();
}
}
loadLocalStorage();
function addTask() {
let newTask = {
taskName: inputTask.value,
checked: false
}
if (inputTask.value !== "") {
// Add task to list and localstorage
toDoList.push(newTask);
showTasks();
updateLocalStorage();
}
}
//Show tasks on the screen
function showTasks() {
let tasksTemplate = '';
toDoList.forEach(function(item, index) {
// Clear input task
document.getElementById("input-task").value = '';
tasksTemplate += `
<li>
<input type="checkbox" class="check" onclick="checkedTask(${index})" ${item.checked ? 'checked' : ''}>
<span class="task">${item.taskName}</span>
<button class="delete-btn" onclick="removeTask(${index})">x</button>
</li>
`;
});
listTask.innerHTML = tasksTemplate;
}
function updateLocalStorage() {
localStorage.setItem("tasks", JSON.stringify(toDoList));
}
function removeTask(index) {
// Remove a task from local storage
toDoList.splice(index, 1);
updateLocalStorage();
showTasks();
// Remove a task from from list
return this.parentNode.remove();
}
// Update state of task and save to local storage
function checkedTask(index) {
toDoList[index].checked = !toDoList[index].checked;
updateLocalStorage();
showTasks();
}
function clearAll() {
localStorage.clear();
while (listTask.firstChild) {
listTask.removeChild(listTask.firstChild);
}
toDoList = [];
}
function toggleTheme(theme) {
const body = document.body;
body.classList.remove('dark', 'light')
if (theme == 'dark') {
body.classList.add('dark')
} else {
body.classList.add('light')
}
}