Toggle
<script src="/src/js/toggle-init.js"></script>
<div
class="l-center"
style="--cr-max-width: var(--bp-20); margin-top: var(--vertical-rhythm)"
>
<label data-toggle class="l-cluster" style="--cl-gap:4px">
<button role="switch" aria-checked="false" type="button"> </button>
<span>Toggle Me</span>
</label>
</div>button[role=switch] {
position: relative;
width: 50px;
height: 25px;
border-radius: 25px;
border: none;
cursor: pointer;
transition: all 600ms ease;
margin-right: 8px;
box-shadow: 0 0 0 0px rgb(255 255 255 / 0.5);
transition: all 600ms ease-in-out;
padding: 0;
&:before {
content: "";
width: 12px;
height: 12px;
border-radius: 12px;
background-color: var(--white);
position: absolute;
top: 50%;
right: 0;
transition: all 600ms ease;
}
&[aria-checked="true"] {
background-color: var(--sl-color-text-accent);
}
&[aria-checked="false"] {
background-color: var(--grey);
}
&[aria-checked="true"]:before {
transform: translate(-8px, -50%);
}
&[aria-checked="false"]:before {
transform: translate(-30px, -50%);
}
}export default class ButtonToggle {
constructor(element) {
this.element = element;
this.element.addEventListener("click", this.clickHandler.bind(this));
}
clickHandler() {
let pressed = this.element.getAttribute("aria-checked") === "true";
this.element.setAttribute("aria-checked", String(!pressed));
}
}A simple, accessible, animated toggle switch