Step 7
25 min
Check off or delete a task using event delegation.
Definition
Event delegation is a technique that consists of placing a single listener on a parent element, instead of placing one on each of its children. It works thanks to event propagation: when you click on a child, the event "bubbles up" from parent to parent, so the parent can detect it.
This technique is particularly useful for dynamically created elements, like our tasks, which don't exist yet when the page loads.
It's time to bring the tasks to life: check a task to complete it, click the cross to delete it. These buttons are created dynamically by JavaScript, which raises a question: how do you listen for clicks on elements that don't exist yet when the page loads?
To answer it, you will proceed in two stages. First, you write the logic that modifies the data, without worrying about clicks. Then, you connect that logic to the user's clicks with a single, well-placed listener.
Start by writing the logic, without worrying about clicks. These functions receive the id of a task:
function toggleTask(id) {
const task = tasks.find((t) => t.id === id);
if (task) {
task.done = !task.done;
}
render();
}
function deleteTask(id) {
tasks = tasks.filter((t) => t.id !== id);
render();
}find returns the first task whose id matches. We then invert its done property with the ! operator (true becomes false, and vice versa).filter creates a new array containing all the tasks except the one whose id is targeted. We reassign tasks, which is why we used let in step 4.render() to redraw the page.If no task matches the id received, find returns undefined. Without the if (task) test, the next line would try to modify a property of undefined and cause an error. This small test makes the function more robust.
The function passed to filter is a test applied to each task: if it returns true, the task is kept in the new array, otherwise it is left out. Here, the t.id !== id test keeps all the tasks whose identifier differs from the one we want to delete. The original array is not modified: a brand-new array replaces it.
In the same way, toggleTask acts like a switch: called once, it completes the task; called a second time, it reopens it.
Rather than adding a listener on each checkbox and each cross (which would have to be recreated on every render), we place a single listener on the list. A click on a child "bubbles up" to the list: this is what we call event delegation. Add this code before the final render(); call:
list.addEventListener("click", (event) => {
const element = event.target.closest(".task");
if (!element) return;
const id = Number(element.dataset.id);
if (event.target.matches(".task__delete")) {
deleteTask(id);
} else if (event.target.matches('input[type="checkbox"]')) {
toggleTask(id);
}
});event.target is the exact element the user clicked (the checkbox, the cross, the text...).closest(".task") goes up the DOM to the parent <li>. If the click happened outside a task, we do nothing.element.dataset.id returns a string, whereas our id values are numbers: we convert with Number(), otherwise the strict comparison === would fail.matches() checks whether the clicked element matches a CSS selector, which lets us tell the cross apart from the checkbox.The click can target an element located inside the task: the checkbox, the cross or the text. closest goes up from that element to the first parent that matches the given selector, and returns null if it finds none. This is what lets us find the whole <li>, and therefore its data-id, wherever exactly the click landed.
When you click on a cross, the browser doesn't only notify the button: the event then travels up to its parent <li>, then to the list <ul>, and so on up to the root of the page. At each step, any listeners present are run.
Our listener on the list therefore receives all the clicks made inside it. Its job is then to identify the target using event.target, then act depending on what it finds: the cross, the checkbox, or something else that we ignore.
Remember that render() destroys and rebuilds all the <li> elements on every call. If we attached a listener to each checkbox or each cross, they would disappear along with the elements and would have to be recreated constantly. Our listener, on the other hand, sits on the list, which is never replaced: it stays active regardless of how many tasks are displayed.
It is also more economical: a single listener is enough for twenty tasks as well as for two hundred.

If nothing happens when you click, open the console with F12 and read the error message: it points to the line involved. Also check that your listener is placed before the final render(); call, and that the class names (task, task__delete) exactly match those used in createTask.
Finally, remember that tasks still disappear when the page is reloaded: saving will come later in the project.
"1727700000000" is never strictly equal to 1727700000000, and nothing happens on click.filter returns a new array that has to be reassigned, which requires let.render() again.find locates a task, filter removes one.In the next step, you will add the filters and the remaining-tasks counter.
Bonus challenge
Make the interface more pleasant:
event.target.matches(".task__text").cursor: pointer to .task__text in CSS to show that it is clickable.deleteTask(999) with an identifier that doesn't exist: what happens? Why is there no error?