Skip to content

Alert Dialog Async Delete

Keep the dialog open while a delete request runs, then close it when the request ends. preventDefault() on actionclicked keeps the dialog open, pending blocks the buttons and Escape and shows a spinner on Confirm, and close() closes the dialog after the request.

  • Website redesign
  • Mobile app
  • Brand guidelines

Delete project?

The project and its files are deleted for every member.

Code

The following example assumes that you have imported the components and set up the theme.

Async Delete
<ul class="project-list">
12 collapsed lines
<li>
<span>Website redesign</span>
<button type="button" class="btn">Delete</button>
</li>
<li>
<span>Mobile app</span>
<button type="button" class="btn">Delete</button>
</li>
<li>
<span>Brand guidelines</span>
<button type="button" class="btn">Delete</button>
</li>
</ul>
<sv-alert-dialog
9 collapsed lines
id="delete-project"
aria-labelledby="delete-project-title"
aria-describedby="delete-project-message"
variant="error"
destructive
confirm-label="Delete"
>
<h2 id="delete-project-title" slot="heading">Delete project?</h2>
<p id="delete-project-message">The project and its files are deleted for every member.</p>
</sv-alert-dialog>
<script type="application/x-typescript" module>
26 collapsed lines
const alertDialog = document.querySelector<AlertDialog>("#delete-project")!;
const title = document.querySelector("#delete-project-title")!;
// Stands in for a request to the server
const deleteProject = () => new Promise(resolve => setTimeout(resolve, 1500));
let projectToDelete: HTMLLIElement;
for (const deleteButton of document.querySelectorAll(".project-list button")) {
deleteButton.addEventListener("click", () => {
projectToDelete = deleteButton.closest("li")!;
title.textContent = `Delete "${projectToDelete.querySelector("span")!.textContent}"?`;
alertDialog.open();
});
}
alertDialog.addEventListener("actionclicked", async event => {
event.preventDefault();
alertDialog.pending = true;
await deleteProject();
alertDialog.pending = false;
projectToDelete.remove();
alertDialog.close();
});
</script>
<style>
17 collapsed lines
.project-list {
display: grid;
gap: 0.5em;
max-inline-size: 24rem;
padding: 0;
margin: 0 auto;
list-style: none;
li {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.5em 0.5em 0.5em 1em;
background-color: var(--sv-gray-6);
border-radius: var(--sv-bdr-rad-md);
}
}
</style>