generated from microverseinc/readme-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
57 lines (51 loc) · 1.49 KB
/
main.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
const form = document.querySelector('.form');
const titleInput = document.querySelector('#first-name');
const authorInput = document.querySelector('#last-name');
const book = document.querySelector('.books');
let books;
const displayBooks = () => {
if (localStorage.getItem('books') == null) {
books = [];
} else {
books = JSON.parse(localStorage.getItem('books'));
}
let display = '';
books.forEach((book, i) => {
display += `
<div class="booksAdded">
<p>${book.title}</p>
<p>${book.author}</p>
<button class="removeBtn" onclick="removeBook(${i})">Remove</button>
<hr />
</div>`;
});
book.innerHTML = display;
};
const addBooks = (Title, Author) => {
if (Title !== '' && Author !== '') {
books.push({ title: Title, author: Author });
localStorage.setItem('books', JSON.stringify(books));
}
displayBooks();
};
window.addEventListener('DOMContentLoaded', () => {
displayBooks();
});
form.addEventListener('submit', (evt) => {
evt.preventDefault();
const titleValue = titleInput.value;
const authorValue = authorInput.value;
addBooks(titleValue, authorValue);
});
/* eslint-disable no-unused-vars */
const removeBook = (id) => {
if (localStorage.getItem('books') == null) {
books = [];
} else {
books = JSON.parse(localStorage.getItem('books'));
}
const bookIndex = books.findIndex((item, i) => i === id);
books.splice(bookIndex, 1);
localStorage.setItem('books', JSON.stringify(books));
displayBooks();
};