-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (83 loc) · 2.59 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
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
import UpdateDate from './modules/luxon.js';
import handlePageChange from './modules/navigation.js';
document.addEventListener('click', (e) => {
handlePageChange(e);
});
UpdateDate();
let books = JSON.parse(localStorage.getItem('books'));
class Book {
constructor(title, author, id) {
this.title = title;
this.author = author;
this.id = id;
}
addBook = () => {
const { title, author, id } = this;
const bookList = { title, author, id };
const errorMsg = document.querySelector('.warning');
books = JSON.parse(localStorage.getItem('books'));
if (title === '' || author === '') {
errorMsg.innerText = 'All fields are required';
} else if (books !== null) {
books.push(bookList);
localStorage.setItem('books', JSON.stringify(books));
books = JSON.parse(localStorage.getItem('books'));
} else {
books = [];
books.push(bookList);
localStorage.setItem('books', JSON.stringify(books));
books = JSON.parse(localStorage.getItem('books'));
}
}
remove = () => {
const { id } = this;
books = books.filter((book) => {
if (book.id === id) {
return false;
}
return true;
});
localStorage.setItem('books', JSON.stringify(books));
}
}
// Display books
const showBooks = (title, author, id) => {
const bookList = document.querySelector('.book-list');
const items = document.createElement('li');
items.innerHTML = `
<div class="item-list"><strong>"${title}"</strong> by <strong>${author}</strong></div>
`;
const removeBtn = document.createElement('button');
removeBtn.textContent = 'Remove';
removeBtn.className = 'remove-btn';
items.append(removeBtn);
bookList.appendChild(items);
removeBtn.addEventListener('click', () => {
const book = new Book(title, author, id);
id = removeBtn.id;
book.remove();
items.remove();
});
};
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('form');
form.addEventListener('submit', (e) => {
e.preventDefault();
const id = Math.floor(Math.random() * 100);
const title = document.getElementById('title').value;
const author = document.getElementById('author').value;
const book = new Book(title, author, id);
book.addBook();
if (title && author) {
showBooks(book.title, book.author, book.id);
}
document.getElementById('title').value = '';
document.getElementById('author').value = '';
});
});
// Appending book to empty object
if (books !== null) {
books.forEach((book) => {
showBooks(book.title, book.author, book.id);
});
}