to do list in javascript

Here's a simple implementation of a to-do list in JavaScript using HTML and CSS as well:

  1. First, let's create the HTML structure for our to-do list. We'll have a container div for our list items, and an input field and button for adding new items:
<div id="list-container">
  <input type="text" id="new-item" placeholder="Add new item...">
  <button id="add-btn">Add</button>
</div>
135 chars
5 lines
  1. Next, we'll use JavaScript to add functionality to our list. We'll start by creating a few variables and selecting our HTML elements:
index.tsx
let items = [];
const listContainer = document.querySelector("#list-container");
const newItemInput = document.querySelector("#new-item");
const addBtn = document.querySelector("#add-btn");
190 chars
5 lines
  1. Now, we'll create a function that adds the new item to our list when the add button is clicked. The function will take the value from the input field, add it to our items array, and create a new list item element:
index.tsx
function addItem() {
  const newItemText = newItemInput.value;
  if (newItemText === "") return; // Don't add empty items
  const newItem = document.createElement("li");
  newItem.innerText = newItemText;
  listContainer.appendChild(newItem);
  items.push(newItemText);
  newItemInput.value = ""; // Clear input field
}
addBtn.addEventListener("click", addItem);
363 chars
11 lines
  1. Let's also add the ability to delete list items. When a list item is clicked, we'll remove it from the items array and remove the corresponding element from the page:
index.tsx
function deleteItem(item, index) {
  items.splice(index, 1);
  listContainer.removeChild(item);
}

listContainer.addEventListener("click", (event) => {
  const clickedItem = event.target;
  const clickedItemIndex = items.indexOf(clickedItem.innerText);
  if (clickedItem.tagName === "LI") {
    deleteItem(clickedItem, clickedItemIndex);
  }
});
346 chars
13 lines
  1. Finally, we'll save our list items to local storage so they persist even when the page is refreshed. We'll also retrieve any existing items from local storage when the page loads:
index.tsx
function saveItems() {
  localStorage.setItem("items", JSON.stringify(items));
}

function loadItems() {
  const storedItems = localStorage.getItem("items");
  if (storedItems) {
    items = JSON.parse(storedItems);
    items.forEach((item) => {
      const newItem = document.createElement("li");
      newItem.innerText = item;
      listContainer.appendChild(newItem);
    });
  }
}

loadItems();
addBtn.addEventListener("click", () => {
  addItem();
  saveItems();
});
473 chars
22 lines

That's it! We now have a simple to-do list that can add and delete items, and saves its state to local storage. Of course, there are many ways to expand on this, such as adding due dates or priorities to items, but this should give you a good starting point.

gistlibby LogSnag