An accessible toggle switch!
See the Live Demo for some examples!
You can import through CDN:
<script type="module" src="https://unpkg.com/@auroratide/toggle-switch/lib/define.js"></script>
Or, you may install through NPM and include it as part of your build process:
$ npm i @auroratide/toggle-switch
import '@auroratide/toggle-switch/lib/define.js'
<toggle-switch>
is an inline markup element that you can use in your HTML document.
<label>Enable: <toggle-switch></toggle-switch></label>
By default, the switch starts in the off position. You can have it start in the on state instead:
<label>Enable: <toggle-switch checked></toggle-switch></label>
Attribute | Default | Description |
---|---|---|
checked |
- | Whether the switch is on or not |
disabled |
- | Whether the switch can change states |
Since toggle-switch
is Just HTMLTM, you can style it the same way you style any HTML tag.
toggle-switch {
width: 5em;
}
The element is composed of two customizable parts:
slider
, the element that slides when toggledtrack
, the element upon which the slider slides
CSS Shadow Parts allow you to customize these elements:
toggle-switch::part(slider) {
background-color: red;
}
toggle-switch::part(track) {
background-color: green;
}
Additionally, using the checked
state, you can define special styling for when the toggle is on.
toggle-switch[checked]::part(track) {
background-color: blue;
}
The element exposes a function to programmatically toggle its state:
Method | Description |
---|---|
toggle() |
Change from off to on, or from on to off |
Each attribute can be accessed as a Javascript property.
elem.checked
elem.disabled
The toggle-switch
element dispatches the following events:
Name | When Triggered |
---|---|
toggle-switch:change |
Any time the state changes (on to off, or off to on) |
The toggle-switch:change
event contains the checked state in its details:
elem.addEventListener('toggle-switch:change', e => {
console.log(e.detail.checked)
})
This custom element is built with accessibility in mind! It follows the WAI-ARIA guidelines for the switch role.
- The element can be focused
- The element can be toggled with
Enter
orSpace