-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
102 lines (90 loc) · 2.78 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
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
97
98
99
100
101
102
const bookTitle = document.getElementById('title');
const bookAuthor = document.getElementById('author');
const btn = document.getElementById('btn-add');
const contactSection = document.querySelector('#contact-section');
const listSection = document.querySelector('#list-section');
const bookForm = document.getElementById('add-section');
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
static storeBooks(books) {
return localStorage.setItem('books', books);
}
static getBooks() {
let books = JSON.parse(localStorage.getItem('books'));
if (!books) {
books = [];
return books;
}
return books;
}
static data = this.getBooks();
static addBookMethod() {
const title = bookTitle.value.toString();
const author = bookAuthor.value.toString();
const book = new Book(title, author);
const inputs = document.querySelectorAll('input');
inputs.forEach((inputs) => {
inputs.value = '';
});
if (title !== '' && author !== '') {
this.data.push(book);
this.storeBooks(JSON.stringify(this.data));
this.displayBooks();
}
}
static removeBook(index) {
this.data = this.data.filter((e, i) => i !== index);
this.storeBooks(JSON.stringify(this.data));
}
static displayBooks() {
this.listSection();
let bookContent = '';
if (this.data.length === 0) {
document.querySelector('.books').innerHTML = 'No Books';
} else {
this.data.map((e, i) => {
bookContent += `<div class="row-div"><p class="title">"${this.data[i].title}"</p>
<p>By</p>
<p class="author">${this.data[i].author}</p>
<button class="remove">Remove</button></div>`;
document.querySelector('.books').innerHTML = bookContent;
const buttons = document.querySelectorAll('button.remove');
buttons.forEach((e, i) => {
buttons[i].addEventListener('click', (event) => {
this.removeBook(this.data.indexOf(this.data[i]));
this.displayBooks();
event.preventDefault();
});
});
return this.data;
});
}
}
static addSection(id) {
const section = document.querySelector(`#${id}`);
section.style.display = 'flex';
return section;
}
static bookForm() {
contactSection.style.display = 'none';
listSection.style.display = 'none';
return this.addSection('add-section');
}
static listSection() {
bookForm.style.display = 'none';
contactSection.style.display = 'none';
return this.addSection('list-section');
}
static contactSection() {
listSection.style.display = 'none';
bookForm.style.display = 'none';
return this.addSection('contact-section');
}
}
btn.addEventListener('click', () => {
Book.addBookMethod();
});
Book.displayBooks();