<html> <head> <title>Pattern</title> </head> <body data-prismjs-copy-timeout="1500"> <h2>What is it</h2> <h2>When to use it</h2> <h2>How to use it</h2> <h2>Example</h2> <p class="switch"> <label for="example-switch">Switch label</label><span id="example-switch" role="switch"></span> </p> <div class="tab-group" id="switches"> <pre class="language-html" data-tab="html"><span id="example-id" role="switch"></span></pre> <pre class="language-pug" data-tab="pug">span#example-id(role="switch")</pre> <pre class="language-css" data-tab="css">[role=switch] { display: -ms-inline-grid; display: inline-grid; border: 1px solid #2e51a1; background-color: #e9e9ea; border-radius: 0.75rem; height: 1.5rem; width: 3rem; -webkit-transition: all 500ms; transition: all 500ms; } [role=switch] > span { display: inline-block; background-color: white; border-radius: 50%; margin: 2%; width: calc(1.5rem - 2%); -webkit-transition: all 500ms; transition: all 500ms; } [role=switch][aria-checked=true] { background-color: #2e51a1; } [role=switch][aria-checked=true] > span { margin-left: calc(1.5rem - 5%); }</pre> <pre class="language-css" data-tab="scss">//- DS2 core (c) 2024 Alexander McIlwraith //- Licensed under CC BY-SA 4.0 @use "sass:math"; $switch-accent: #2e51a1 !default; // switch background when switched right (on/ true) $switch-background: #e9e9ea !default; // switch background when switched left (off / false) $switch-color: #ffffff !default; // the colour of the switch $switch-height: 1.5rem !default; @mixin switch { [role='switch'] { display: inline-grid; border: 1px solid $switch-accent; background-color: $switch-background; border-radius: math.div($switch-height, 2); height: $switch-height; width: #{$switch-height * 2}; transition: all 500ms; > span { display: inline-block; background-color: white; border-radius: 50%; margin: 2%; width: calc(#{$switch-height} - 2%); transition: all 500ms; } &[aria-checked="true"] { background-color: $switch-accent; > span { margin-left: calc(#{$switch-height} - 5%); } } } }</pre> <pre class="language-js" data-tab="js">//- DS2 core (c) 2024 Alexander McIlwraith //- Licensed under CC BY-SA 4.0 function flip(e) { let sw = e.currentTarget; switch(sw.getAttribute("aria-checked")) { case "true": sw.setAttribute("aria-checked", "false"); break; case "false": sw.setAttribute("aria-checked", "true"); break; } }; function init(callback){ let sw = document.querySelectorAll("[role='switch']"); for (let i=0; i < sw.length; i++) { sw[i].innerHTML = "<span></span>"; sw[i].setAttribute("aria-checked", "false"); sw[i].setAttribute("tabindex", "0"); sw[i].addEventListener("click", flip, false); sw[i].addEventListener("keypress", flip, false); } } export {init};</pre> </div> </body> </html>