-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
63 lines (57 loc) · 1.67 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
const bookList = document.querySelector('#books');
let bookIndex;
class Books {
static display() {
const books = Books.getBooks();
bookList.innerHTML = '';
for (bookIndex = 0; bookIndex < books.length; bookIndex += 1) {
const book = books[bookIndex];
bookList.innerHTML += `
<li class="book d-flex">
<h2> "${book.title}" by ${book.author}</h2>
<button type="button" class="remove" onclick="removeBook(${bookIndex})">Remove</button>
</li>`;
}
}
static add(book) {
const books = Books.getBooks();
books.push(book);
localStorage.setItem('books', JSON.stringify(books));
Books.display();
}
static remove(bookId) {
if (bookId !== null) {
const books = Books.getBooks();
books.splice(bookId, 1);
localStorage.setItem('books', JSON.stringify(books));
Books.display();
}
}
static clearFields() {
document.querySelector('#title').value = '';
document.querySelector('#author').value = '';
}
static getBooks() {
const savedBooks = localStorage.getItem('books');
if (savedBooks !== null) {
return JSON.parse(localStorage.getItem('books'));
}
return [];
}
}
document.addEventListener('DOMContentLoaded', () => Books.display());
document.querySelector('#Add').addEventListener('click', (e) => {
e.preventDefault();
const newBook = {
author: document.querySelector('#author').value,
title: document.querySelector('#title').value,
};
if (newBook.title.length > 2 && newBook.author.length > 2) {
Books.add(newBook);
Books.clearFields();
}
});
const removeBook = (bookId) => Books.remove(bookId);
if (bookIndex === -1) {
removeBook();
}