Odin Project - Objects
https://www.theodinproject.com/courses/javascript/lessons/objects-and-object-constructors
by Lakshay Akula
HTML
<body>
<h1>
My Library
</h1>
<ul class='books'>
</ul>
</body>
JavaScript
const myLibrary = [];
function Book(title, author, pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
Book.prototype.info = function() {
return `${this.title} by ${this.author}, ${this.pages} pages`
}
function addBookToLibrary(title, author, pages) {
myLibrary.push(new Book(title, author, pages));
}
function displayBooks() {
const booksList = document.querySelector('.books');
booksList.innerHTML = ''
if (myLibrary.length === 0) {
booksList.innerHTML += `Add books to your library!`
}
for(let i= 0; i<myLibrary.length; i++) {
book = myLibrary[i];
booksList.innerHTML += `
<li>${book.info()}</li>
<button class='remove-book' data-book=${i}> Remove </button>
`
}
// Enable remove button
const removeBookButtons = document.querySelectorAll(".remove-book");
removeBookButtons.forEach(button => button.addEventListener('click', removeBook));
}
function removeBook(event) {
const bookToRemove = this.dataset.book;
myLibrary.splice(bookToRemove, 1);
displayBooks();
console.log(bookToRemove);
}
// Populate library
addBookToLibrary('The Hobbit', 'J.R.R. Tolkein', 295);
addBookToLibrary('1984', 'George Orwell', 187);
addBookToLibrary('The Pearl', 'John Steinbeck', 91);
displayBooks();