forked from GSG-CF05/Todo-App-Basil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
95 lines (77 loc) · 2.69 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
94
95
let mainInput = document.querySelector(`#main-input`);
let submitBtn = document.querySelector(`#btn`);
let toDoUl = document.querySelector(`ul`);
let editInput = document.querySelector(`#edit-input`);
let editBtn = document.querySelector(`#submit`);
let indexOfParent = 0;
let toDoStorage = [];
submitBtn.addEventListener(`click`, addNewItem);
document.addEventListener(`DOMContentLoaded`, getTodoListOnLoad);
toDoUl.addEventListener('click', deleteEdit);
function addNewItem(e){
e.preventDefault();
if(mainInput.value!=""){
let todoDiv= document.createElement('div')
let newItem = `
<li>${mainInput.value}</li>
<i class="fas fa-pen edit"></i>
<i class="far fa-trash-alt delete"></i>
`;
todoDiv.innerHTML= newItem;
toDoUl.appendChild(todoDiv)
todoDiv.classList.add('box')
saveToLocalStorage(mainInput.value);
}
mainInput.value="";
}
function saveToLocalStorage(todo){
if(localStorage.getItem('toDoStorage')==null){
toDoStorage=[];
}
else {
toDoStorage=JSON.parse(localStorage.getItem('toDoStorage'))
}
toDoStorage.push(todo);
localStorage.setItem('toDoStorage', JSON.stringify(toDoStorage))
}
function getTodoListOnLoad(){
if(localStorage.getItem('toDoStorage')){
toDoStorage= JSON.parse(localStorage.getItem('toDoStorage'))
}
toDoStorage.forEach(todo => {
let todoDiv= document.createElement('div')
let newItem = `
<li>${todo}</li>
<i class="fas fa-pen edit"></i>
<i class="far fa-trash-alt delete"></i>
`;
todoDiv.innerHTML= newItem;
toDoUl.appendChild(todoDiv)
todoDiv.classList.add('box')
});
}
function deleteEdit(e){
if(e.target.classList.contains('delete')){
let parentItem = e.target.parentNode;
let array=JSON.parse(localStorage.getItem('toDoStorage'))
let parentItemDelete=array.indexOf(parentItem.innerText)
array.splice(parentItemDelete, 1)
localStorage.setItem('toDoStorage', JSON.stringify(array))
parentItem.remove();
}
if(e.target.classList.contains('edit')){
let itemText = e.target.parentNode.innerText;
let allItemsText = JSON.parse(localStorage.getItem('toDoStorage'))
indexOfParent = allItemsText.indexOf(itemText.toLowerCase());
editInput.value = allItemsText[indexOfParent];
editInput.style.display = `block`;
mainInput.style.display = `none`;
editBtn.style.display = `block`;
submitBtn.style.display = `none`;
}
}
editBtn.addEventListener (`click`, function () {
let allItemsText=JSON.parse(localStorage.getItem('toDoStorage'));
allItemsText[indexOfParent] = editInput.value;
localStorage.setItem('toDoStorage', JSON.stringify(allItemsText));
});