-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
82 lines (78 loc) · 2.4 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class Books {
bookList = [];
constructor() {
this.bookList = JSON.parse(localStorage.getItem('Books')) || [];
}
addBook(book) {
this.bookList.push(book);
this.storeList();
}
removeBook(id) {
this.bookList = this.bookList.filter((book) => book.id !== id);
this.storeList();
}
storeList() {
localStorage.setItem('Books', JSON.stringify(this.bookList));
}
}
const books = new Books();
const pages = ['#list', '#add', '#contact'];
const menu = document.querySelector('.header-menu');
const links = document.querySelectorAll('.header-menu a');
const contents = document.querySelectorAll('.content');
const list = document.querySelector('.content-list');
const form = document.querySelector('.content-form');
function displayContent(hash) {
pages.forEach((page) => {
const link = links[pages.indexOf(page)];
const content = contents[pages.indexOf(page)];
if (page === hash && content.classList.contains('visible') === false) {
link.classList.add('active');
content.classList.add('visible');
setTimeout(() => content.classList.add('rotate'), 1);
} else if (content.classList.contains('visible')) {
link.classList.remove('active');
content.classList.remove('visible');
content.classList.remove('rotate');
}
});
}
function displayBooks() {
if (books.bookList.length === 0) {
list.innerHTML = '<h2>No available books</h2>';
} else {
list.innerHTML = '';
const fragment = new DocumentFragment();
books.bookList.forEach((book) => {
const item = document.createElement('li');
let itemHTML = `<p>"${book.title}" by ${book.author}</p>`;
itemHTML += `<button id="${book.id}">Remove</button>`;
item.innerHTML = itemHTML;
fragment.appendChild(item);
});
list.appendChild(fragment);
}
}
function contentEvent(event) {
event.preventDefault();
if (event.target.hash !== '') {
displayContent(event.target.hash);
}
}
function addEvent(event) {
event.preventDefault();
books.addBook({ id: `${Date.now()}`, title: form.title.value, author: form.author.value });
displayBooks();
form.reset();
}
function removeEvent(event) {
if (event.target.id !== '') {
books.removeBook(event.target.id);
displayBooks();
}
}
menu.addEventListener('click', contentEvent);
list.addEventListener('click', removeEvent);
form.addEventListener('submit', addEvent);
displayContent('#list');
displayBooks();