forked from MoRaad97/Awesome-Books
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
61 lines (45 loc) · 1.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
// DOM Element from HTML
const bookForm = document.getElementById('book-form');
const bookContainer = document.querySelector('.books');
// Get an input from HTML by it's parent
const inName = bookForm.book;
const inAuthor = bookForm.author;
// Create an array to push books on that
const books = JSON.parse(localStorage.getItem('books')) || [];
const addBooks = (book, author) => {
books.push({
book,
author,
});
localStorage.setItem('books', JSON.stringify(books));
return { book, author };
};
// Create HTML Elements and Books Characterstics In DOM
const createBookElements = ({ book, author }, index) => {
const bookDiv = document.createElement('div');
const bookName = document.createElement('h2');
const authorName = document.createElement('h2');
const btn = document.createElement('button');
bookDiv.classList.add('container');
// Fill the elements
bookName.innerText = book;
authorName.innerText = author;
btn.innerHTML = 'Delete';
btn.addEventListener('click', (event) => {
event.target.parentElement.remove();
books.splice(index, 1);
localStorage.setItem('books', JSON.stringify(books));
});
// For showing the above staff in browser we have to append them
bookDiv.append(bookName, authorName, btn);
// This div must also append to some where in HTML so
bookContainer.appendChild(bookDiv);
};
books.forEach(createBookElements);
bookForm.onsubmit = (event) => {
event.preventDefault();
const newBook = addBooks(inName.value, inAuthor.value);
createBookElements(newBook);
inName.value = '';
inAuthor.value = '';
};