Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var itemsList = [];
- var messageEl = document.querySelector(".no-item-message");
- // get the ul element
- const ulEl = document.getElementById("list-items");
- /**
- * This function adds a todo item to the list
- * @param {Event} event
- */
- function addItem(event) {
- event.preventDefault();
- // get the entered text and trim empty spaces
- const inputEl = document.getElementById("newTodo");
- const newItem = inputEl.value.trim();
- // check if text is empty
- if (newItem === "") {
- showError("Please enter a text");
- return;
- }
- // checking whether the item already exist
- if (itemsList.indexOf(newItem) != -1) {
- showError("Item already exist");
- return;
- }
- hideError();
- // add the todo item to the ul element
- ulEl.innerHTML +=
- `<li>
- <div class="item-wrapper">
- <span class="item-text">${newItem}</span>
- <button class="remove-item" onclick="removeItem(event, '${newItem}')">
- -
- </button>
- </div>
- </li>`;
- //add the item also to the array
- itemsList.push(newItem);
- //clear input
- inputEl.value = "";
- }
- /**
- *
- * @param {Event} event
- * @param {String} item
- */
- function removeItem(event, item) {
- // removing the li element from the ul
- const removeButton = event.target;
- const liEl = removeButton.parentElement.parentElement;
- ulEl.removeChild(liEl);
- // removing the item from the array
- const itemIdex = itemsList.indexOf(item)
- itemsList.splice(itemIdex, 1);
- if(itemsList.length ==0){
- showError("Please add an item")
- }
- }
- /**
- * show the empty items message
- * @param {String} errorMessage
- */
- function showError(errorMessage) {
- //get the empty message element
- messageEl.innerText = errorMessage;
- messageEl.style.display = "block";
- }
- /**
- * hide the empty items message
- */
- function hideError() {
- //get the empty message element
- messageEl.style.display = "none";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement