Advertisement
Lulunga

exam prep DOM 01. BookUni

Oct 23rd, 2019
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve() {
  2.     const [titleInput, yearInput, priceInput] = Array.from(document.querySelectorAll('input'));
  3.     const addBtn = document.querySelector('button');
  4.     const totalProfitHeader = Array.from(document.querySelectorAll('h1'))[1];
  5.     const [oldShelf, newShelf] = Array.from(document.getElementsByClassName('bookShelf'));
  6.     let totalSum = 0;
  7.  
  8.     addBtn.addEventListener("click", function (e) {
  9.         e.preventDefault(); //when button is in a formprevents reloading the page after each btton click
  10.         const title = titleInput.value;
  11.         const year = Number(yearInput.value);
  12.         const price = Number(priceInput.value);
  13.  
  14.         if (title !== '' && price > 0 && year > 0) {
  15.             if (year >= 2000) {
  16.                 createBook(false, title, year, price, newShelf);
  17.             } else {
  18.                 createBook(true, title, year, price, oldShelf);
  19.             }
  20.         }
  21.     });
  22.     function createBook(isOld, title, year, price, shelf) {
  23.         price = isOld ? price * 0.85 : price;
  24.         const bookElement = document.createElement('div');
  25.         const p = document.createElement('p');
  26.         const buyBtn = document.createElement('button');
  27.  
  28.         bookElement.classList.add('book');
  29.         p.textContent = `${title} [${year}]`;
  30.         buyBtn.textContent = `Buy it only for ${price.toFixed(2)} BGN`;
  31.         buyBtn.addEventListener('click', function (e) {
  32.             totalSum += price;
  33.             this.parentNode.parentNode.removeChild(this.parentNode);
  34.             totalProfitHeader.textContent = `Total Store Profit: ${totalSum.toFixed(2)} BGN`;
  35.         });
  36.         bookElement.appendChild(p);
  37.         bookElement.appendChild(buyBtn);
  38.         if (!isOld) {
  39.             const moveBtn = document.createElement('button');
  40.             moveBtn.textContent = `Move to old section`;
  41.             bookElement.appendChild(moveBtn);
  42.  
  43.             moveBtn.addEventListener('click', function (e) {
  44.                 this.parentNode.parentNode.removeChild(this.parentNode);
  45.                 createBook(true, title, year, price, oldShelf);
  46.             });
  47.         }
  48.         shelf.appendChild(bookElement);
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement