Skip to content

Instantly share code, notes, and snippets.

@fitrh
Last active September 23, 2021 04:09
Show Gist options
  • Save fitrh/10f01ff946747e36d8fd2a4130b1cb10 to your computer and use it in GitHub Desktop.
Save fitrh/10f01ff946747e36d8fd2a4130b1cb10 to your computer and use it in GitHub Desktop.
Lecture 6 - Snippet Web Dev Classrom

Lecture 6 - Sept 22 2021

Get element

const inputItem = document.getElementById('input-item');
const btnAddItem = document.getElementById('btn-add-item');
const listContainer = document.querySelector('.list');

Basic Databse

const database = new Map();

Handle click event for add button

btnAddItem.addEventListener('click', () => {
  const ITEM_KEY = inputItem.value.toUpperCase();
  const ITEM_VALUE = inputItem.value;

  // NOTE: Create element
  const listItem = document.createElement('li');
  const textItem = document.createElement('p');
  const btnDelete = document.createElement('button');
  const counter = document.createElement('button');

  // WARN: Handle error, empty input
  if (ITEM_VALUE === '') {
    alert("Item Name can't be blank");
    inputItem.focus();
    return;
  }

  // WARN: Check for duplication
  if (database.has(ITEM_KEY)) {
    alert(`You already have ${ITEM_VALUE}`);
    inputItem.value = '';
    inputItem.focus();
    return;
  }

  // NOTE: Add the new item to database
  database.set(ITEM_KEY, ITEM_VALUE);

  // NOTE: Add attribute
  listItem.classList.add('list-item'); // NOTE: Add Class

  // NOTE: Add value
  textItem.textContent = ITEM_VALUE;
  btnDelete.textContent = 'Delete';
  
  // NOTE: The counter should be dynamicly show how much do we have for this item
  counter.textContent = 5;

  // NOTE: Combine elements
  listItem.append(textItem, btnDelete, counter);
  listContainer.appendChild(listItem);

  // NOTE: Handle click event for delete button
  btnDelete.addEventListener('click', () => {
    listContainer.removeChild(listItem);
  });

  inputItem.value = '';
  inputItem.focus();
});

TASK

Add delete confirmation

  • If user confirms yes, delete the item if it is the only item, otherwise decrease the counter
  • If user confirm no/decline/press ESC, do not delete the item

Item counter

  • If user input the same item, display a counter showing how many related item do we have
  • If there are only items, do not display the counter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment