Toggle
View Example
<div class="l-center" style="--cr-max-width: var(--bp-20); margin-top: var(--vertical-rhythm)">
<label class="l-cluster">
<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: white;
position: absolute;
top: 50%;
right: 0;
transition: all 600ms ease;
}
&[aria-checked="true"] {
background-color: green;
}
&[aria-checked="false"] {
background-color: #cccccc;
}
&[aria-checked="true"]:before {
transform: translate(-8px, -50%);
}
&[aria-checked="false"]:before {
transform: translate(-30px, -50%);
}
}
button[role=switch].animating {
animation-name: fadeIn;
animation-fill-mode: forwards;
animation-duration: 1s;
}
@keyframes fadeIn {
to {
box-shadow: 0 0 0 6px rgb(255 255 255 / 0);
}
}
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));
this.element.classList.add("animating");
this.element.setAttribute('disabled', true);
setTimeout(() => {
this.element.classList.remove("animating");
this.element.removeAttribute('disabled');
}, 1000);
}
}
A simple, accessible, animated toggle switch