forked from iamshaunjp/JavaScript-DOM-Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
92 lines (85 loc) · 2.53 KB
/
app.js
File metadata and controls
92 lines (85 loc) · 2.53 KB
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
const bookList = document.querySelector('#book-list ul');
const bookForm = document.forms['add-book'];
const hideBooks = document.querySelector('#hide');
const bookRead = document.querySelectorAll('.book-complete');
const searchBooks = document.forms['search-books'].querySelector('input');
//delete Function
bookList.addEventListener('click', function (e) {
if (e.target.matches('.delete')) {
deleteBooks(e.target);
} else if (e.target.matches('.book-complete')) {
completeRead(e.target);
}
});
searchBooks.addEventListener('keyup', (e) => {
const searchTerm = e.target.value.toLowerCase();
const books = bookList.querySelectorAll('li');
books.forEach((book) => {
const title = book.querySelector('.name').textContent;
if (title.toLowerCase().includes(searchTerm)) {
book.style.display = 'block';
} else {
book.style.display = 'none';
}
});
});
//hide All books
hideBooks.addEventListener('change', (ev) => {
if (hideBooks.checked) {
bookList.style.display = 'none';
} else {
bookList.style.display = 'initial';
}
});
//delete books
function deleteBooks(ev) {
const li = ev.parentElement;
bookList.removeChild(li);
}
//complete read books
function completeRead(ev) {
ev.addEventListener('change', () => {
let title = ev.parentElement.querySelector('.name');
if (ev.checked) {
title.style.textDecoration = 'line-through';
title.style.color = 'red';
} else {
title.style.textDecoration = 'initial';
title.style.color = 'initial';
}
});
}
// add Book Function
bookForm.addEventListener('submit', (e) => {
e.preventDefault();
let text = e.target.title.value;
let newLI = createAndAppendElement('li', bookList, null, null, undefined);
let checkBox = createAndAppendElement('input', newLI, null, 'book-complete', (e) => {
e.setAttribute('type', 'checkbox');
});
createAndAppendElement('label', newLI, null, null, (e) => {
e.htmlFor = checkBox.className;
});
createAndAppendElement('span', newLI, null, 'name', (e) => {
e.textContent = text;
});
createAndAppendElement('span', newLI, null, 'delete', (e) => {
e.textContent = 'delete';
});
e.target.title.value = '';
});
//helper append function to doc
function createAndAppendElement(tag, parent, id, className, callback) {
const element = document.createElement(tag);
parent.append(element);
if (id !== null) {
element.id = id;
}
if (className !== null) {
element.className = className;
}
if (callback !== undefined) {
callback(element);
}
return element;
}