-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (51 loc) · 1.47 KB
/
index.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
const btnEl = document.getElementById("btn");
const appEl = document.getElementById("app");
getNotes().forEach((note) => {
const noteEl = createNoteEl(note.id, note.content);
appEl.insertBefore(noteEl, btnEl);
});
function createNoteEl(id, content) {
const element = document.createElement("textarea");
element.classList.add("note");
element.placeholder = "Empty Note";
element.value = content;
element.addEventListener("dblclick", () => {
const warning = confirm("Do you want to delete this note?");
if (warning) {
deleteNote(id, element);
}
});
element.addEventListener("input", () => {
updateNote(id, element.value);
});
return element;
}
function deleteNote(id, element) {
const notes = getNotes().filter((note)=>note.id != id)
saveNote(notes)
appEl.removeChild(element)
}
function updateNote(id, content) {
const notes = getNotes();
const target = notes.filter((note) => note.id == id)[0];
target.content = content;
saveNote(notes);
}
function addNote() {
const notes = getNotes();
const noteObj = {
id: Math.floor(Math.random() * 100000),
content: "",
};
const noteEl = createNoteEl(noteObj.id, noteObj.content);
appEl.insertBefore(noteEl, btnEl);
notes.push(noteObj);
saveNote(notes);
}
function saveNote(notes) {
localStorage.setItem("note-app", JSON.stringify(notes));
}
function getNotes() {
return JSON.parse(localStorage.getItem("note-app") || "[]");
}
btnEl.addEventListener("click", addNote);