kstoyanov

01. Christmas Gifts Delivery-10 December 2019-exam

Oct 22nd, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solution() {
  2.   const sections = document.querySelectorAll('section');
  3.  
  4.   const addSection = sections[0];
  5.   const listSection = sections[1];
  6.   const sentSection = sections[2];
  7.   const deiscardedSection = sections[3];
  8.  
  9.   const input = addSection.querySelector('input');
  10.   const addBtn = addSection.querySelector('button');
  11.  
  12.   addBtn.addEventListener('click', addGift);
  13.  
  14.   function addGift(e) {
  15.     if (!input.value) { return; }
  16.     const li = document.createElement('li');
  17.     li.className = 'gift';
  18.     li.textContent = input.value;
  19.  
  20.     const sendBtn = creteButton('sendButton', 'Send');
  21.     sendBtn.addEventListener('click', (e) => {
  22.       const li = document.createElement('li');
  23.       li.textContent = e.target.parentElement.textContent.slice(0, e.target.parentElement.textContent.lastIndexOf('Send'));
  24.  
  25.       const sentGifts = sentSection.querySelector('ul');
  26.       sentGifts.appendChild(li);
  27.  
  28.       e.target.parentElement.remove();
  29.     });
  30.  
  31.     const discardBtn = creteButton('discardButton', 'Discard');
  32.     discardBtn.addEventListener('click', (e) => {
  33.       const li = document.createElement('li');
  34.       li.textContent = e.target.parentElement.textContent.slice(0, e.target.parentElement.textContent.lastIndexOf('Send'));
  35.  
  36.       const disctredGifts = deiscardedSection.querySelector('ul');
  37.       disctredGifts.appendChild(li);
  38.  
  39.       e.target.parentElement.remove();
  40.     });
  41.  
  42.     li.appendChild(sendBtn);
  43.     li.appendChild(discardBtn);
  44.  
  45.     const allGifts = listSection.querySelector('ul');
  46.     allGifts.appendChild(li);
  47.  
  48.     sortGifts();
  49.     input.value = '';
  50.  
  51.     function sortGifts() {
  52.       const gifts = Array.from(listSection.querySelector('ul').children);
  53.       gifts.sort((a, b) => (a.textContent.slice(0, a.textContent.indexOf('Send')))
  54.         .localeCompare(b.textContent.slice(0, b.textContent.lastIndexOf('Send'))));
  55.       allGifts.innerHTML = '';
  56.       gifts.forEach((element) => {
  57.         allGifts.appendChild(element);
  58.       });
  59.     }
  60.  
  61.     function creteButton(btnId, btnText) {
  62.       const button = document.createElement('button');
  63.       button.id = btnId;
  64.       button.textContent = btnText;
  65.  
  66.       return button;
  67.     }
  68.   }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment