Advertisement
OpataJoshua

Untitled

Aug 4th, 2022
1,141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var itemsList = [];
  2. var messageEl = document.querySelector(".no-item-message");
  3. // get the ul element
  4. const ulEl = document.getElementById("list-items");
  5.  
  6. /**
  7.  * This function adds a todo item to the list
  8.  * @param {Event} event
  9.  */
  10. function addItem(event) {
  11.   event.preventDefault();
  12.   // get the entered text and trim empty spaces
  13.   const inputEl = document.getElementById("newTodo");
  14.  
  15.   const newItem = inputEl.value.trim();
  16.  
  17.   // check if text is empty
  18.   if (newItem === "") {
  19.     showError("Please enter a text");
  20.     return;
  21.   }
  22.   // checking whether the item already exist
  23.   if (itemsList.indexOf(newItem) != -1) {
  24.     showError("Item already exist");
  25.     return;
  26.   }
  27.   hideError();
  28.  
  29.   // add the todo item to the ul element
  30.   ulEl.innerHTML +=
  31.   `<li>
  32.     <div class="item-wrapper">
  33.       <span class="item-text">${newItem}</span>
  34.       <button class="remove-item" onclick="removeItem(event, '${newItem}')">
  35.         -
  36.       </button>
  37.     </div>
  38.   </li>`;
  39.  
  40.   //add the item also to the array
  41.   itemsList.push(newItem);
  42.  
  43.   //clear input
  44.   inputEl.value = "";
  45. }
  46.  
  47. /**
  48.  *
  49.  * @param {Event} event
  50.  * @param {String} item
  51.  */
  52. function removeItem(event, item) {
  53.   // removing the li element from the ul
  54.   const removeButton = event.target;
  55.   const liEl =  removeButton.parentElement.parentElement;
  56.   ulEl.removeChild(liEl);
  57.  
  58.   // removing the item from the array
  59.   const itemIdex = itemsList.indexOf(item)
  60.   itemsList.splice(itemIdex, 1);
  61.  
  62.   if(itemsList.length ==0){
  63.     showError("Please add an item")
  64.   }
  65. }
  66.  
  67. /**
  68.  * show the empty items message
  69.  * @param {String} errorMessage
  70.  */
  71. function showError(errorMessage) {
  72.   //get the empty message element
  73.   messageEl.innerText = errorMessage;
  74.   messageEl.style.display = "block";
  75. }
  76.  
  77. /**
  78.  * hide the empty items message
  79.  */
  80. function hideError() {
  81.   //get the empty message element
  82.   messageEl.style.display = "none";
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement