-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
101 lines (73 loc) · 2.46 KB
/
app.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
96
97
98
99
100
101
import './script/components/index.js'
// import './script/view/newData.js'
import home from './script/view/home.js';
document.addEventListener('DOMContentLoaded', () => {
home();
loadNotes();
setFormListener();
// Tahun realtime footer
const currentYearElement = document.getElementById('currentYear');
const currentYear = new Date().getFullYear();
currentYearElement.textContent = currentYear;
});
// Validasi Form custom
const form = document.querySelector('.notes-form');
const titleInput = form.elements.noteTitle;
const descInput = form.elements.noteDesc;
form.addEventListener('submit', (e) => e.preventDefault());
titleInput.addEventListener('invalid', (e) => {
e.target.setCustomValidity('');
if (!e.target.validity.valid) {
e.target.setCustomValidity('Wajib diisi.');
return;
};
});
descInput.addEventListener('invalid', (e) => {
e.target.setCustomValidity('');
if (!e.target.validity.valid) {
e.target.setCustomValidity('Wajib diisi.');
return;
};
});
// ===================== Add Note to Local Storage ==========================
function setFormListener() {
const notesForm = document.getElementById('notesForm');
notesForm.addEventListener('submit', (e) => {
e.preventDefault();
const noteTitle = document.getElementById('noteTitle').value;
const noteDesc = document.getElementById('noteDesc').value;
const note = {
id: generateUniqueId(),
title: noteTitle,
body: noteDesc,
createdAt: new Date().toISOString(),
archived: false,
}
let notes = JSON.parse(localStorage.getItem('notes')) || [];
notes.push(note);
localStorage.setItem('notes', JSON.stringify(notes))
this.reset();
loadNotes();
});
}
function generateUniqueId() {
const timestamp = Date.now().toString();
const randomString = Math.random().toString(36).substring(2, 8);
return `notes-${timestamp}-${randomString}`;
}
function loadNotes() {
const noteListElement = document.querySelector('note-list');
// noteListElement.innerHTML = '';
const notes = JSON.parse(localStorage.getItem('notes')) || [];
notes.forEach(note => {
const noteItemElement = document.createElement('note-item');
noteItemElement.note = note;
noteListElement.append(noteItemElement);
});
}
/* Reload browser ketika button diclick, agar data di local storage
langsung muncul :) */
const saveBtn = document.getElementById('saveBtn')
saveBtn.addEventListener('click', function() {
location.reload();
});