switch button docs

Switch Button

An interactive UI element that represents a particular boolean function.

Published Last updated: 5.1.0 Change log Github NPM
Twig Usage
{% include '@bolt-components-switch-button/switch-button.twig' with {
  label: 'This is the label for the switch button'
} only %}
Schema
Note: when assigning component props as HTML attributes on a web component, make sure to use kebab-case.
Prop Name Description Type Default Value Option(s)
attributes

A Drupal attributes object. Applies extra HTML attributes to this component's parent container.

object
button_attributes

A Drupal attributes object. Applies extra HTML attributes to this component's <button> element.

object
label *

Render a label in front of the switch button.

any
on

Controls the active state of the switch button. Sets button state to "on" by default.

boolean false
Install Install
npm install @bolt/components-switch-button
Dependencies @bolt/core-v3.x

switch button

Basic Switch Button A switch button handles boolean functions that happen instantly. Important Notes: Switch Button should be used to handle changes that happen instantly. It should not be used in a form which requires a submit action. For rendering boolean options within a form, use a checkbox input instead. The label prop can accept anything. For better control of text styling, pass the headline component into the label prop. The component does not ship with JavaScript. Reference the sample code snippet below to see how to toggle on/off state with the aria-checked attribute. When writing HTML, make sure to follow the sample code snippet below and render all neccessary id, class, and attributes on the <label> and the <button> elements. Demo
Twig
{% include '@bolt-components-switch-button/switch-button.twig' with {
  label: 'Toggle me',
  attributes: {
    class: 'js-target-the-switch-button-container'
  },
} only %}
HTML
<label class="js-target-the-switch-button-container c-bolt-switch-button" for="bolt-switch-button-123">
  <div class="c-bolt-switch-button__label">Toggle me</div>
  <button class="c-bolt-switch-button__button" type="button" id="bolt-switch-button-123" role="switch" aria-checked="false">
    <span class="c-bolt-switch-button__button-text c-bolt-switch-button__button-text--checked">on</span>
    <span class="c-bolt-switch-button__button-text c-bolt-switch-button__button-text--unchecked ">off</span>
  </button>
</label>
JavaScript
const switchButton = document.querySelector(
  '.js-target-the-switch-button-container button[role="switch"]',
);

switchButton.addEventListener('click', e => {
  const el = e.target;
  const isChecked = el.getAttribute('aria-checked') === 'true';

  el.setAttribute('aria-checked', isChecked ? false : true);
});