When a user clicks the delete button, we want to delete the corresponding task.
Deleting tasks
A Todolist contains many tasks. Each task contains a delete button. In this case, the best way to delete a task is to use an event delegation pattern.
todolist.addEventListener('click', event => {
// Deletes a task
})
We only want to activate the event listener if the user clicks on the delete button. We bail if the clicked element is not a delete button.
todolist.addEventListener('click', event => {
if (!event.target.matches('.task__delete-button')) return
// Deletes a task
})
If the user clicks on the delete button, we want to find the task element to remove. The task element is the parent element of the delete button.
todolist.addEventListener('click', event => {
if (!event.target.matches('.task__delete-button')) return
// Deletes a task
const taskElement = event.target.parentElement
})
We can use removeChild to delete a task. This means we need to know what’s the parentElement of the task too.
todolist.addEventListener('click', event => {
if (!event.target.matches('.task__delete-button')) return
// Deletes a task
const taskElement = event.target.parentElement
taskList.removeChild(taskElement)
})
Triggering the empty state
We want to trigger the empty state if there are no more tasks in the .todolist__tasks. This empty state can only be triggered if there are no whitespaces in the HTML (because of the way we built it).
Each time we delete a task, we want to check if there are any tasks left in the taskList. If there are no tasks left in the taskList, we set the innerHTML to '' to remove all whitespace.
todolist.addEventListener('click', event => {
if (!event.target.matches('.task__delete-button')) return
const taskElement = event.target.parentElement
// Removes the task
taskList.removeChild(taskElement)
// Triggers empty state
if (taskList.children.length === 0) {
taskList.innerHTML = ''
}
})