top-javascript-projects/library-app/js/javascript.js

82 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

2024-12-30 15:44:02 -05:00
const myLibrary = [];
2025-01-04 08:18:56 -05:00
const container = document.getElementById("main");
2025-01-04 09:08:58 -05:00
const addBookBtn = document.getElementById("addBook");
const newBookForm = document.querySelector("form");
2025-01-04 09:08:58 -05:00
const dialog = document.querySelector("dialog");
2024-12-30 15:44:02 -05:00
function Book(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read
// this.info = function() {
// return `${this.title} by ${this.author}, ${this.pages}, ${this.read}`
// }
}
function addBookToLibrary(title,author,pages,read) {
let newBook = new Book(title,author,pages,read)
myLibrary.push(newBook)
}
2025-01-05 09:36:53 -05:00
function createCard (book, index){
2025-01-04 08:18:56 -05:00
const card = document.createElement("div");
const classList = ["p-6", "border", "border-slate-300",
"bg-white", "rounded-xl", "shadow-xl", "flex", "flex-col", "gap-x-4"];
card.classList.add(...classList);
2025-01-05 09:36:53 -05:00
card.dataset.index = index
2025-01-04 08:18:56 -05:00
Object.keys(book).forEach((element) => {
if (element == 'title') {
let item = document.createElement('h2');
item.textContent = `${book[element]}`;
item.classList.add(...["font-bold", "text-2xl"])
card.appendChild(item);
} else {
let item = document.createElement('p');
item.textContent = `${element}: ${book[element]}`;
card.appendChild(item);
}
})
container.appendChild(card);
}
2025-01-04 09:08:58 -05:00
addBookBtn.addEventListener("click", () => {
2025-01-05 09:36:53 -05:00
dialog.showModal();
2025-01-04 09:08:58 -05:00
})
2025-01-04 08:18:56 -05:00
newBookForm.addEventListener("submit", (e)=> {
2025-01-05 09:36:53 -05:00
e.preventDefault();
2025-01-05 09:36:53 -05:00
const inputs = [...newBookForm.elements];
let book = [];
inputs.forEach((item) => {
2025-01-05 09:36:53 -05:00
book.push(item.value);
// console.log(item.value);
// console.log(item.type);
})
2025-01-05 09:36:53 -05:00
clearForm();
dialog.close();
})
2025-01-05 09:36:53 -05:00
function clearForm() {
const inputs = [...newBookForm.elements];
inputs.forEach((item) => {
if(item.type == 'submit') return;
item.value = ""
})
}
2024-12-30 15:44:02 -05:00
addBookToLibrary("Test Book", "Kyle", "300", true)
addBookToLibrary("How the Grinch Stole Christmas", "Dr. Seuss", "12", false)
// console.log(myLibrary)
2025-01-04 08:18:56 -05:00
2025-01-05 09:36:53 -05:00
myLibrary.forEach((book, index) => createCard(book, index))