Switch
A pure vanilla JS implementation of Zag JS Switch
Anatomy
The Switch component consists of the following data-part
root
label
hidden-input
control
thumb
Data attributes
Each switch can be set with different settings with the following data-attribute.
Callbacks
Each switch component can receive callbacks that can be used to respond to user interaction with custom behavior.
You must add a custom id and an event listener for your event name
document.getElementById("my-callback-switch")
?.addEventListener("my-callback-switch-event", (event) => {
console.log("Received event:", (event as CustomEvent).detail);
});
Open your browser's console to see the events received when you check or uncheck the above switch
Checked State Control
Switch checked state can be control with data attributes on any element
You must set a custom id for your switch, as the default is randomly generated
data-check-switch="switch-id"
data-uncheck-switch="switch-id"
You also dispatch an event named switch:set-checked
to the switch id with a boolean value
const el = document.getElementById("my-switch");
if (el) {
el.dispatchEvent(
new CustomEvent("switch:set-checked", {
detail: { value: true },
})
);
} else {
console.warn("Element with ID 'my-switch' not found");
}
Use with Form
Switch can be used inside a form
You must set the id of the form and the name of the switch
data-form="form-id"
data-name="switch-name"
You can also add the value of the switch. Default to : "on"
data-value="yes"
You can use the results from the form as you wish
const form = document.getElementById('my-form') as HTMLFormElement | null;
const result = document.getElementById('result') as HTMLDivElement | null;
if (form && result) {
form.addEventListener('submit', (e: Event) => {
e.preventDefault();
const formData = new FormData(form);
const newsletter = (formData.get('newsletter') as string) || 'no';
result.textContent = `Submitted: newsletter: ${newsletter}`;
});
}
Modifier
Each switch can be styled with modifiers.
You can mix as many modifiers on the same switch, however you can choose only one choice per modifer
For convenience the default variant name is omited, meaning there is no need to add the default name class
Color
Set the color of each button
Options: base(default), brand, alert
Size
Set the size of each button
Options: md(default), sm, lg, xl
Shape
Set the shape of each button
Options: inherit(default), circle
Mix
Mix as many modifiers for each button
Custom (Tailwind)
If you are using Tailwind styling, you can customize each switch with Tailwind utilities
Templates
Switch components is available in the followng templates
-
Corex template
Default corex templates. It provides the global, semantic and components tokens
-
Modex template
Based on Corex default template, it adds dark and light mode option to the tokens
-
Themex template
Based on the Corex default template, it adds theming capabilities as well as light and dark mode options to the tokens.