todo lists

by superyngo

HTML

<body>
    <input type="text" placeholder="請輸入待辦事項" />
    <button onclick="add()">新增</button>
    <select id="selectImportance">
      <option value="normal">一般</option>
      <option value="important">重要</option>
      <option value="urgent">緊急</option>
    </select>
    <hr />
    <div id="root"></div>
  </body>

CSS

*,
*::before,
*::after {
  box-sizing: border-box;
}

img,
picture,
svg,
video {
  display: block;
}

* {
  margin: 0;
  padding: 0;
  font: inherited;
}

html {
  color-scheme: dark light;
}

body {
  min-height: 100svh;
}

li {
  list-style: none;
}

JavaScript

const selectElement = document.querySelector("#selectImportance");
const input = document.querySelector("input");
const importanceBackgroundColor = {
  normal: "white",
  important: "orange",
  urgent: "red",
};
selectElement.addEventListener("change", selectImportanceChange);

var todos = [
  {
    title: "倒垃圾",
    category: "normal",
  },
  {
    title: "繳電話費",
    category: "important",
  },
  {
    title: "採買本週食材",
    category: "urgent",
  },
];

function render() {
  //console.log(todos);
  const root = document.querySelector("#root");
  root.textContent = "";
  const ul = document.createElement("ul");
  root.append(ul);
  todos.forEach((todo, index) => {
    const li = document.createElement("li");
    const delBtn = document.createElement("button");
    li.textContent = todo.title;
    li.style.backgroundColor = importanceBackgroundColor[todo.category];
    delBtn.textContent = "刪除";
    delBtn.onclick = () => del(index);
    ul.append(li, delBtn);
  });
}

function add() {
  todos.push({
    title: input.value,
    category: selectElement.options[selectElement.selectedIndex].value,
  });
  // console.log(input);
  render();
}

function del(index) {
  todos.splice(index, 1);
  render();
}

function selectImportanceChange() {
  input.style.backgroundColor =
    importanceBackgroundColor[
      selectElement.options[selectElement.selectedIndex].value
    ];
}

render();