Skip to content

Latest commit

 

History

History

input-switch

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

Implement something like <input type=checkbox switch>

npm version Workflow status

Demo

Examples

<script type="importmap">
  {
    "imports": {
      "@w0s/input-switch": "...",
      "@w0s/shadow-append-css": "..."
    }
  }
</script>
<script type="module">
  import InputSwitch from '@w0s/input-switch';

  customElements.define('x-input-switch', InputSwitch);
</script>

<label><x-input-switch
  name="foo"
  value="1"
  checked=""
  disabled=""
  storage-key="foo"
></x-input-switch> switch</label>

Attributes

name [optional]
Name of the element to use for form submission. (Same as name attribute of <input> Element)
value [optional]
Value of the form control. If omitted, the value is on. (Same as value attribute of <input> Element)
checked [optional]
Whether the control is checked. (Same as checked attribute of <input> Element)
disabled [optional]
Whether the form control is disabled. (Same as disabled attribute of <input> Element)
storage-key [optional]
Save this value as localStorage key when switching controls. (value is true or false depending on the check state)

Style customization

The following CSS custom properties can be used to customize the style.

name deault Description
--outline-offset 1px outline-offset property value of switch control
--block-size 1em Block size of switch control
--inline-size 2em Inline size of switch control
--animation-duration 0.5s Time a transition animation (transition-duration property)
--track-color-on #2299ff Track color when switch is on
--track-color-off #cccccc Track color when switch is off
--track-color-disabled-on #666666 Track color when switch is on disabled
--track-color-disabled-off #666666 Track color when switch is off and disabled
--thumb-radius calc(0.5em - 1px) Radius of slider ball
--thumb-color #ffffff Color of slider ball

The shadow DOM of the switch looks like this.

<x-input-switch class="my-switch">
  #shadow-root (open)
  <div part="track"></div>
  <div part="thumb"></div>
</x-input-switch>

Therefore, the ::part CSS pseudo-element may be used to customize the style as desired.

.my-switch {
  --outline-offset: ...;
  --block-size: ...;
  ...

  &::part(track) {
    ...
  }

  &::part(thumb) {
    ...
  }
}

However, customizations other than CSS custom properties may be broken in future version updates.