Basic Task Management
12 min read
Complete a Task
Complete a Task
Next, make the task check button change the task’s completed state.
1. Update the Rendered Task
Inside renderTasks(), replace the task HTML with:
taskElement.innerHTML = `
<div class="task-main">
<button
class="task-check"
type="button"
data-action="toggle"
data-id="${task.id}"
aria-label="${task.completed ? "Mark task active" : "Complete task"}"
></button>
<span class="task-title">${task.title}</span>
</div>
`;
2. Show Completed Tasks Correctly
After assigning the HTML, add:
if (task.completed) {
taskElement.classList.add("completed");
}
The prepared CSS already contains the completed-task styling.
3. Handle the Check Button
Add this event listener after renderTasks() is defined:
taskList.addEventListener("click", (event) => {
const button = event.target.closest('[data-action="toggle"]');
if (!button) {
return;
}
const task = tasks.find((item) => item.id === button.dataset.id);
if (!task) {
return;
}
task.completed = !task.completed;
renderTasks();
});
4. Test the Feature
Add a few tasks.
Click the check button on one of them.
The task should switch to its completed appearance.
Click it again to make the task active.
Checkpoint
You can now switch tasks between active and completed states.