Dialogs that behave like dialogs
Build a reusable delete confirmation flow
Reuse one confirmation dialog for every task while keeping the selected record and destructive action explicit.
A board with twenty tasks does not need twenty dialogs. One confirmation dialog can receive the selected task, display its name, and perform deletion only after a clear confirmation value returns.
Store the pending task element in JavaScript when a Delete button is activated. Put the task title into a normal text node, never into innerHTML. After close, remove the pending card only when returnValue is confirm, then clear the reference so stale state cannot affect a later interaction.
const board = document.querySelector("#board")
const confirmDialog = document.querySelector("#confirm-dialog")
const confirmName = confirmDialog.querySelector("[data-task-name]")
let pendingTask = null
board.addEventListener("click", event => {
const button = event.target.closest("[data-action=delete]")
if (!button) return
pendingTask = button.closest("[data-task-id]")
confirmName.textContent = pendingTask.querySelector("h2").textContent
confirmDialog.showModal()
})
confirmDialog.addEventListener("close", () => {
if (confirmDialog.returnValue === "confirm") pendingTask?.remove()
pendingTask = null
})
The confirmation text should name the affected task and explain the consequence. “Delete Write homepage? This cannot be undone” is better than a generic “Are you sure?” because the user can verify both target and cost.
Make the destructive button visually and textually clear, but do not rely on color alone. Put initial focus on Cancel for an irreversible action. If deletion is reversible, an immediate action plus Undo may be less disruptive than a confirmation dialog.
Server deletion can fail after the dialog closes. Treat the visible removal as optimistic only when you can restore the card. Otherwise keep it present, mark it busy, wait for a successful response, and show an error outside the closed dialog if the request fails.
Add Delete buttons to several cards and reuse one dialog. Confirm one deletion, cancel another, and rapidly open the flow for different tasks. Verify only the named card changes. If the wrong task disappears, check when pendingTask is assigned and cleared, and prevent multiple modal opens while an operation is active.
Lesson completed