bitty installation snippets examples documentation q&a

snippets

switch

--
  • The b.switch() method generates an HTML button designed to be styled as a switch. It's goal is to provide a switch interface with basic functionality. It's not designed to try to accommodate every use case.
  • The specific CSS Styles are the responsibility of the page. This is the CSS use on this page:
    view css
    :root {
      --bitty-switch-off: #778;
      --bitty-switch-on: #0a0;
      --bitty-switch-text: white;
    }
    
    .bitty-switch {
      display: block;
    }
    
    .bitty-switch button {  
      background-color: var(--bitty-switch-off);
      border: 1px solid rgb(255 255 255 / 0);
      border-radius: 1rem;
      color: var(--bitty-switch-text);
      height: 1.2rem;
      padding: 0;
      position: relative;
      transform: translateY(0.25rem);
      width: 3.1rem;
    }
    
    .bitty-switch button:hover {  
      border: 1px solid var(--bitty-switch-text);
      color: var(--bitty-switch-text);
    }
    
    .bitty-switch button[aria-checked="true"]  {
      background-color: var(--bitty-switch-on);
    }
    
    .bitty-switch button :nth-child(1):after,
    .bitty-switch button :nth-child(1):before {
      position: absolute;
      top: 50%;
      transform: translateY(-53%);
    }
    
    .bitty-switch button :nth-child(2):after,
    .bitty-switch button :nth-child(2):before {
      border-radius: 1rem;
      height: 1rem;
      width: 1rem;
      content: "";
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
    
    .bitty-switch button[aria-checked="true"] :nth-child(1):before {
      content: "on";
      left: 0.35rem;
    }
    
    .bitty-switch button[aria-checked="true"] :nth-child(2):before {
      background: var(--bitty-switch-text);
      right: 0.25rem;
    }
    
    .bitty-switch button[aria-checked="false"] :nth-child(1):after {
      content: "off";
      right: 0.35rem;
    }
    
    .bitty-switch button[aria-checked="false"] :nth-child(2):after {
      background: var(--bitty-switch-text);
      left: 0.25rem;
    }
  • See the b.switch() portion of the bitty functions section in the documentation for more details.

html

<div data-r="initSwitch"></div>
<div data-r="toggle">--</div>

javascript

export const b = { init: "initSwitch" };

export function initSwitch(_, __, el) {
  const subs = {
    __PREPEND__: "snippet switch",
    __SEND__: "toggle",
  };
  el.replaceChildren(b.switch(subs));
}

export function toggle(_, sender, el) {
  sender.setAria("checked", !sender.ariaAsBool("checked"));
  el.innerHTML = sender.ariaAsBool("checked") ? "on" : "off";
}
  • The data-r="toggle" receiving element does not get an initial value. It's only updated when a switch occurs.
  • See the next snippet for a version that initializes the value from localStorage.