Skip to content

Switch — JavaScript

The markup and CSS classes are on the HTML & CSS page. This page covers wiring it up.

Initialize

ts
import { Switch } from '@popovandrii/ui-elements'
import '@popovandrii/ui-elements/style.css'

const sw = new Switch()
// sw.destroy() when the markup goes away

Events

ts
document.addEventListener('ui-switch-change', (e) => {
  const { id, value } = (e as CustomEvent).detail // value: "true" | "false"
})

Programmatic API

ts
const el = document.querySelector('.UIsw')!

sw.setValue(el, true)                    // toggle on, emits + flashes
sw.setValue(el, false, { silent: true }) // no event
sw.destroy()                             // unbind everything
sw.scan()                                // (re)bind newly added markup

Usage with Vue

vue
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { Switch } from '@popovandrii/ui-elements'
import '@popovandrii/ui-elements/style.css'

const root = ref<HTMLElement>()
let sw: Switch | null = null

function onChange(e: Event) {
  const { id, value } = (e as CustomEvent).detail // value: "true" | "false"
  console.log(id, value)
}

onMounted(() => {
  sw = new Switch({}, false, { root: root.value! })
  root.value!.addEventListener('ui-switch-change', onChange)
})
onUnmounted(() => {
  root.value?.removeEventListener('ui-switch-change', onChange)
  sw?.destroy()
})
</script>

<template>
  <div ref="root">
    <div class="UIsw primary" role="switch" tabindex="0">
      <label class="UIsw-label" for="wifi">Wi-Fi</label>
      <input type="checkbox" id="wifi" checked hidden />
      <span class="UIsw-slider"></span>
    </div>
  </div>
</template>

The shared patterns (observe, a composable, dynamic lists) are in the full Usage with Vue guide — they apply to every component.