-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
96 lines (80 loc) · 2.57 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
96
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
}
const bookStorage = [];
/* eslint max-classes-per-file: ["error", 2] */
class CreateBook {
static addBook(newBook, index) {
const library = document.querySelector('#books-container');
if (!localStorage.getItem('books')) {
const noBook = document.createElement('p');
noBook.innerHTML = 'No books in library';
library.appendChild(noBook);
}
const container = document.createElement('div');
container.innerHTML = `
<div class="book-item">
<p>"${newBook.title}" by ${newBook.author} </p>
<button class="remove-btn" data-remove=${index}>Delete</button>
</div>
`;
library.appendChild(container);
bookStorage.push(newBook);
}
// delete function
static deleteBook(index) {
bookStorage.splice(index, 1);
CreateBook.updateLocalStorage();
}
// set local storage
static updateLocalStorage() {
localStorage.setItem('books', JSON.stringify(bookStorage));
}
// fetch local storage
static getLocalStorage() {
if (localStorage.getItem('books')) {
const books = JSON.parse(localStorage.getItem('books'));
books.forEach((book, index) => {
const newBook = new Book(book.title, book.author);
CreateBook.addBook(newBook, index);
});
} else {
localStorage.setItem('books', JSON.stringify(bookStorage));
}
const deleteBtn = document.querySelectorAll('.remove-btn');
deleteBtn.forEach((btn) => {
btn.addEventListener('click', (e) => {
const index = e.target.dataset.remove;
CreateBook.deleteBook(index);
CreateBook.updateLocalStorage();
e.target.parentElement.remove();
});
});
}
}
const form = document.querySelector('.books-form');
form.addEventListener('submit', (e) => {
e.preventDefault();
const title = document.querySelector('#title').value;
const author = document.querySelector('#author').value;
if (title !== '' && author !== '') {
const newBook = new Book(title, author);
CreateBook.addBook(newBook);
CreateBook.updateLocalStorage(newBook);
document.querySelector('#title').value = '';
document.querySelector('#author').value = '';
document.querySelector('#title').focus();
}
const deleteBtn = document.querySelectorAll('.remove-btn');
deleteBtn.forEach((btn) => {
btn.addEventListener('click', (e) => {
const index = e.target.dataset.remove;
CreateBook.deleteBook(index);
e.target.parentElement.remove();
});
});
});
CreateBook.getLocalStorage();