Skip to content

Toggle Switch Async Setting

clicked is cancelable, so the switch holds its state while the change saves to the server. The switch is disabled during the request, and toggle() commits the result once it lands.

Saved

Code

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

Async Setting
<div class="async-setting">
7 collapsed lines
<div class="row">
<div class="text">
<label for="backup-switch">Automatic backups</label>
<small class="status">Saved</small>
</div>
<sv-toggle-switch id="backup-switch" checked></sv-toggle-switch>
</div>
</div>
<script type="application/x-typescript" module>
15 collapsed lines
const backup = document.querySelector<ToggleSwitch>("#backup-switch")!;
const status = document.querySelector(".async-setting .status")!;
backup.addEventListener("clicked", async event => {
event.preventDefault();
backup.disabled = true;
status.textContent = "Saving...";
await new Promise(resolve => setTimeout(resolve, 900));
backup.disabled = false;
backup.toggle();
status.textContent = "Saved";
});
</script>
<style>
29 collapsed lines
.async-setting {
max-inline-size: 24rem;
margin-inline: auto;
background-color: var(--sv-gray-7);
border: 1px solid var(--sv-gray-5);
border-radius: var(--sv-bdr-rad-lg);
.row {
display: flex;
gap: 1em;
align-items: center;
padding: 0.85em 1em;
.text {
display: grid;
flex: 1;
gap: 0.15em;
label {
font-weight: 600;
cursor: pointer;
}
small {
color: var(--sv-gray-3);
}
}
}
}
</style>