-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
74 lines (63 loc) · 1.73 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
'use strict';
// ELEMENTS SELECTED
const input = document.querySelector("input");
const ul = document.querySelector("ul");
// <<<--- Beginning Point --->>>
let data = {
'items': []
};
fetchItems();
input.focus()
// ADD, FETCH and RESET function
function addItem() {
data['items'].push(input.value);
input.value = "";
localStorage.setItem('data', JSON.stringify(data));
location.reload();
}
function fetchItems() {
if (localStorage.getItem(`data`) != null) {
data = JSON.parse(localStorage.getItem(`data`));
data['items'].forEach((element, index) => {
// ELEMENTS CREATED
const li = document.createElement("li");
const p = document.createElement("p");
const span = document.createElement("span");
// MAIN LOGIC
p.innerText = element;
li.id = index;
span.innerHTML = '<div class="close-card-btn">×</div>';
li.append(p);
li.append(span);
ul.appendChild(li);
});
}
}
function reset() {
localStorage.clear();
location.reload();
}
function deleteItem(index) {
data['items'].splice(index, 1);
localStorage.setItem('data', JSON.stringify(data));
location.reload();
}
// Event Listeners
input.addEventListener("keypress", (e) => {
// keyCode of ENTER Key is 13
if (input.value.length != 0 && e.keyCode === 13) {
addItem();
}
})
window.addEventListener('click', (e) => {
if (e.target.closest('span')) {
const index = e.target.closest('span').parentElement.id;
deleteItem(index);
}
else if (e.target.closest('#reset')) {
reset();
}
else if (e.target.closest('#add')) {
addItem();
}
})