The HTML
<h1>My tasks</h1>
<form id="add-form">
<label for="task">New task</label>
<input id="task" required maxlength="80">
<button>Add</button>
</form>
<ul id="list"></ul>
<p id="left"></p>
Using a <form> means pressing Enter adds a task, and required stops empty tasks.
Keep the data in one place
Store the tasks in an array and redraw the list from it whenever something changes. This "single source of truth" keeps the page and the data in step:
let tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
function save() {
localStorage.setItem("tasks", JSON.stringify(tasks));
}
localStorage saves text in the browser, so the array is converted to JSON text with JSON.stringify and back with JSON.parse.
Draw the list
const list = document.querySelector("#list");
const left = document.querySelector("#left");
function render() {
list.replaceChildren();
tasks.forEach((task, i) => {
const li = document.createElement("li");
const box = document.createElement("input");
box.type = "checkbox";
box.checked = task.done;
box.setAttribute("aria-label", "Done: " + task.text);
box.addEventListener("change", () => { task.done = box.checked; update(); });
const text = document.createElement("span");
text.textContent = task.text;
if (task.done) text.style.textDecoration = "line-through";
const del = document.createElement("button");
del.textContent = "Delete";
del.addEventListener("click", () => { tasks.splice(i, 1); update(); });
li.append(box, text, del);
list.append(li);
});
const open = tasks.filter(t => !t.done).length;
left.textContent = open + (open === 1 ? " task left" : " tasks left");
}
function update() { save(); render(); }
The task text is set with textContent, never innerHTML. That way, if someone types HTML or a script into the box, it is shown as plain text instead of running.
Add new tasks
const form = document.querySelector("#add-form");
const input = document.querySelector("#task");
form.addEventListener("submit", event => {
event.preventDefault(); // stay on the page
const text = input.value.trim();
if (!text) return;
tasks.push({ text, done: false });
input.value = "";
update();
});
render();
event.preventDefault() stops the browser's normal form submission, which would reload the page.
Ideas to extend it
- Add a "Clear completed" button using
filter. - Add filter buttons for All, Active and Done.
- Let people edit a task by double-clicking it.
- Style done tasks with a CSS class instead of an inline style.
Try it yourself
Put the HTML and the script together in Unays Code, run it, add a few tasks and reload the preview to check they are remembered. Then pick one idea from the list above.
This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].