-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.js
62 lines (51 loc) · 1.52 KB
/
main2.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
const app = document.getElementById("app");
const button = app.querySelector("button");
getNotes().forEach( note => {
let element = createElement(note.id, note.content);
app.insertBefore(element, button);
});
button.addEventListener("click", addNote);
function getNotes() {
return JSON.parse(localStorage.getItem("key-note") || "[]");
}
function saveNotes(notes) {
localStorage.setItem("key-note", JSON.stringify(notes));
}
function createElement(id, content) {
const element = document.createElement("textarea");
element.value = content;
element.classList.add("note");
element.placeholder = "db click to remove";
element.addEventListener("change", () => {
updateNote(id, element.value);
});
element.addEventListener("dblclick", () => {
let ask = confirm("are you sure?");
if (ask) {
deleteNote(id, element);
}
})
return element;
}
function deleteNote(id, element) {
let notes = getNotes().filter(note => note.id !== id);
saveNotes(notes);
app.removeChild(element);
}
function updateNote(id, newContent) {
let notes = getNotes();
let target = notes.filter(note => note.id === id);
target[0].content = newContent;
saveNotes(notes);
}
function addNote() {
let notes = getNotes();
let noteObj = {
id: Math.floor(Math.random()* 1000),
content: "",
};
notes.push(noteObj);
saveNotes(notes);
let newNote = createElement(noteObj.id, noteObj.content);
app.insertBefore(newNote, button);
}