Od szwagra dla szwagra

mail@pastecode.io avatar
unknown
javascript
a year ago
2.4 kB
2
Indexable
Never
const mainInput = document.querySelector("input");
const firstList = document.querySelector("#pierwszaLista");
const secondList = document.querySelector("#drugaLista");
const form = document.querySelector("form");
const historyInput = document.querySelector(".history");

let mainTasksList = [];
let historyList = [];
let taskNum = 0;

const getFirstListElementHTML = (taskText) => {
  const taskElementWrapper = document.createElement('li');
  const taskSpan = document.createElement('span');
  const removeTaskButton = document.createElement('button');
  const taskId = `task${taskNum}`;

  // dodanie id zeby latwiej bylo usuwac elementy
  taskElementWrapper.id = taskId;
  taskSpan.innerText = taskText;
  removeTaskButton.innerText = 'Usuń';

  const taskPosition = mainTasksList.length - 1;
  removeTaskButton.addEventListener('click', () => {
    mainTasksList.splice(taskPosition,1);
    document.querySelector(`#${taskId}`).remove();
  });

  // dodawanie elementow do htmla
  taskElementWrapper.appendChild(taskSpan);
  taskElementWrapper.appendChild(removeTaskButton);

  ++taskNum;

  return taskElementWrapper;
}

const getSecondListElementHTML = (taskText) => {
  const listElement = document.createElement('li');
  listElement.innerText = taskText;
  listElement.addEventListener('click', () => firstList.appendChild(getFirstListElementHTML(taskText)));

  return listElement;
}

const showHistory = (e) => {
  secondList.innerHTML = '';
  const { value } = e.target;
  const matchingTasks = historyList.filter((task) => task.includes(value));

  matchingTasks.forEach((taskText) => secondList.appendChild(getSecondListElementHTML(taskText)));
};


const addTask = (event) => {
  event.preventDefault();

  // warto sie tego zapisu nauczyc
  // jak masz obiekt const obj = { a: 123, b: 234 } to mozesz zrobic
  // const { a } = obj;
  // i wtedy możesz sobie używać zmiennej a

  const { value } = mainInput;

  if (!value) { // czyli jak bedzie pustym stringiem
    return;
  }

  // dodawanie do glownej listy i do historii
  mainTasksList.push(value);
  historyList.push(value);

  // tworzenie elementu html
  const taskElementWrapper = getFirstListElementHTML(value);
  firstList.appendChild(taskElementWrapper);

  mainInput.value = '';
};

form.addEventListener("submit", addTask);
historyInput.addEventListener("input", showHistory);