-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
71 lines (57 loc) · 2.17 KB
/
Copy pathscript.js
File metadata and controls
71 lines (57 loc) · 2.17 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
'use strict';
let todocontainer = document.querySelector('.todo-list');
let todoTextBox = document.getElementById("todo");
window.onload = function () {
let savedTodos = JSON.parse(localStorage.getItem("todos")) || [];
savedTodos.forEach(todo => createTodoElement(todo.todoTask, todo.checked));
};
function createTodoElement(todoText, isChecked) {
let newLi = document.createElement("li");
if (isChecked) newLi.classList.add("chosen");
let newp = document.createElement("p");
newp.innerHTML = todoText;
newLi.append(newp);
let newspan = document.createElement("span");
newspan.innerHTML = 'X';
newLi.append(newspan);
todocontainer.append(newLi);
}
function addTodo() {
if (todoTextBox.value === '') {
alert("Empty Todo Cannot Be Added.");
} else {
let todoText = todoTextBox.value;
let todos = JSON.parse(localStorage.getItem("todos")) || [];
let flag = 0;
todos.forEach(todo => {
if(todoText===todo.todoTask){
flag = 1;
}
});
if(!flag){
let newTodo = { todoTask: todoText, checked: false };
todos.push(newTodo);
localStorage.setItem("todos", JSON.stringify(todos));
createTodoElement(todoText, false);}
else{
alert(`${todoText} already exists.`);
}
}
todoTextBox.value = '';
}
todocontainer.addEventListener("click", (hit) => {
let todos = JSON.parse(localStorage.getItem("todos")) || [];
if (hit.target.tagName === "P") {
let parentLi = hit.target.parentElement;
parentLi.classList.toggle("chosen");
let index = Array.from(todocontainer.children).indexOf(parentLi);
todos[index].checked = parentLi.classList.contains("chosen");
localStorage.setItem("todos", JSON.stringify(todos));
} else if (hit.target.tagName === "SPAN") {
let parentLi = hit.target.parentElement;
let index = Array.from(todocontainer.children).indexOf(parentLi);
todos.splice(index, 1);
localStorage.setItem("todos", JSON.stringify(todos));
parentLi.remove();
}
}, false);