npm.io
2.1.0 • Published 5d ago

@19h47/switch

Licence
ISC
Version
2.1.0
Deps
0
Size
21 kB
Vulns
0
Weekly
20

@19h47/switch

A switch is an on/off control that represents a binary setting. It provides an accessible, keyboard-navigable interface following the ARIA switch pattern, reads its state from the markup, and dispatches native DOM events when toggled.

Installation

pnpm add @19h47/switch

HTML

<div role="switch" tabindex="0" aria-checked="false">
	<span class="label">Notifications</span>
	<span class="switch"><span></span></span>
	<span class="on" aria-hidden="true">On</span>
	<span class="off" aria-hidden="true">Off</span>
	<div hidden><input type="checkbox" /></div>
</div>

When disabled, use aria-disabled="true" and tabindex="-1".

<div role="switch" tabindex="-1" aria-checked="false" aria-disabled="true">
	<span class="label">Disabled switch</span>
	<span class="switch"><span></span></span>
	<div hidden><input type="checkbox" /></div>
</div>

JavaScript

import Switch from '@19h47/switch';

const $switch = document.querySelector('[role="switch"]');

const switchButton = new Switch($switch);
switchButton.init();

Keyboard support

Key Function
Tab
  • Moves keyboard focus to the switch.
Space
Enter
  • Toggle switch between on and off.

Event

Events are dispatched on the switch element.

Event Description
Switch.activate Fired when activated.
Switch.deactivate Fired when deactivated.
import Switch from '@19h47/switch';

const $switch = document.querySelector('[role="switch"]');

const switchButton = new Switch($switch);
switchButton.init();

$switch.addEventListener('Switch.deactivate', () => {
	console.log('deactivated');
});

$switch.addEventListener('Switch.activate', () => {
	console.log('activated');
});

Acknowledgment

Keywords