@phucbm/data-toggle
v0.1.0
Published
Toggle class in elements via [data-toggle='class-name']
Maintainers
Readme
@phucbm/data-toggle
A lightweight, flexible TypeScript utility for toggling CSS classes via data attributes. Perfect for building interactive UI components without framework dependencies.
Features
✨ Zero dependencies - fully self-contained
🎯 Framework agnostic - works with any JavaScript framework or vanilla JS
🔧 Flexible targeting - toggle classes on any element via selectors
📱 Smart defaults - auto-prevents default for links and buttons
🎪 Event-driven - dispatches custom events for easy integration
⚡ Debounced clicks - built-in debouncing support
♿ Accessible - optional aria-expanded / aria-controls sync and Escape to close
🔄 Multiple instances - create separate instances with different configurations
🛡️ TypeScript - fully typed for better DX
Installation
npm i @phucbm/data-togglepnpm add @phucbm/data-toggleQuick Start
HTML
<!-- Toggle class on <html> element -->
<button data-toggle="dark-mode">Toggle Dark Mode</button>
<!-- Toggle multiple classes at once (comma-separated) -->
<button data-toggle="dark-mode,sidebar-open">Toggle Dark Mode + Sidebar</button>
<!-- Toggle class on specific element -->
<button data-toggle="sidebar-open" data-toggle-element=".sidebar">Toggle Sidebar</button>
<div class="sidebar">Sidebar content</div>
<!-- Multiple toggles work independently -->
<button data-toggle="menu-active">Menu</button>
<button data-toggle="modal-open" data-toggle-element="#modal">Modal</button>JavaScript
import { createDataToggle } from '@phucbm/data-toggle';
// Initialize once - tracks all [data-toggle] elements
const toggle = createDataToggle();
// That's it! All buttons with data-toggle now workAdvanced Usage
Custom Configuration
const toggle = createDataToggle({
// Use custom data attributes
toggleAttribute: 'data-my-toggle',
elementAttribute: 'data-my-target',
// Change default target (instead of <html>)
defaultTarget: document.body,
// Control click behavior
preventDefault: true, // or false, or 'auto' (default)
// Add debouncing
debounceDelay: 100,
// Enable debug logging
debug: true
});Programmatic Control
// Toggle classes programmatically
toggle.toggle('dark-mode'); // Toggle on default target
toggle.toggle('sidebar-open', '.sidebar'); // Toggle on specific element
toggle.toggle('dark-mode,nav-hidden'); // Toggle multiple classes at once
toggle.toggle('menu-open', undefined, false); // Force off (true forces on), e.g. close the menu on resize
// Check if classes are active
if (toggle.isActive('dark-mode')) {
console.log('Dark mode is ON');
}
// Check specific elements
if (toggle.isActive('sidebar-open', '.sidebar')) {
console.log('Sidebar is open');
}
// isActive returns true only if ALL specified classes are active
if (toggle.isActive('dark-mode,nav-hidden')) {
console.log('Both classes are active');
}
// Refresh after DOM changes
document.body.innerHTML += '<button data-toggle="new-feature">New</button>';
toggle.refresh(); // Now the new button works
// Clean up
toggle.destroy(); // Removes all event listenersEvent Listening
// Listen for toggle events
document.addEventListener('datatoggle', (event) => {
const { classNames, target, trigger, active } = event.detail;
console.log(`Classes "${classNames.join(', ')}" were ${active ? 'added' : 'removed'}`);
console.log('Target element:', target);
console.log('Trigger element:', trigger);
// Example: Save theme preference
if (classNames.includes('dark-mode')) {
localStorage.setItem('theme', active ? 'dark' : 'light');
}
});Examples
Dark Mode Toggle
<button data-toggle="dark-mode" class="theme-toggle">
🌙 Toggle Dark Mode
</button>.dark-mode {
background: #1a1a1a;
color: #ffffff;
}Mobile Menu
One class on <html>, any number of triggers: the hamburger, a close button, the backdrop.
<button data-toggle="menu-open" data-toggle-escape aria-label="Menu">☰</button>
<nav id="mobile-menu" class="mobile-menu">
<button data-toggle="menu-open">Close</button>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
<div class="backdrop" data-toggle="menu-open" aria-hidden="true"></div>createDataToggle({aria: true});
// Every button/link with data-toggle="menu-open" gets aria-expanded="true|false";
// Escape closes it (data-toggle-escape on the trigger, or escape: true for all)..mobile-menu {
transform: translateX(-100%);
transition: transform 0.3s ease;
}
.menu-open .mobile-menu {
transform: translateX(0);
}Modal Dialog
<button data-toggle="modal-open" data-toggle-element="#my-modal">
Open Modal
</button>
<div id="my-modal" class="modal">
<div class="modal-content">
<h2>Modal Title</h2>
<p>Modal content here...</p>
<button data-toggle="modal-open" data-toggle-element="#my-modal">
Close
</button>
</div>
</div>Sidebar with Body Scroll Lock
const toggle = createDataToggle();
document.addEventListener('datatoggle', (e) => {
if (e.detail.classNames.includes('sidebar-open')) {
// Lock body scroll when sidebar opens
document.body.style.overflow = e.detail.active ? 'hidden' : '';
}
});API Reference
createDataToggle(config?: DataToggleConfig): DataToggleInstance
Creates a new data toggle instance.
Configuration Options:
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| selector | string | '[data-toggle]' | CSS selector for toggle elements |
| toggleAttribute | string | 'data-toggle' | Attribute containing the class name(s), comma-separated |
| elementAttribute | string | 'data-toggle-element' | Attribute containing target selector |
| defaultTarget | Element | document.documentElement | Default element to toggle classes on |
| defaultElementSelector | string | '' | Fallback selector for targets |
| preventDefault | boolean \| 'auto' | 'auto' | Prevent default click behavior |
| debug | boolean | false | Enable debug logging |
| debounceDelay | number | 0 | Debounce delay in milliseconds |
| aria | boolean | false | Keep aria-expanded on button and link triggers (<a>, <button>, any [role]) in step with their classes, on load and after every change. Adds aria-controls when data-toggle-element points to an element with an id (an existing aria-controls is kept) |
| escape | boolean | false | The Escape key turns off every active toggle |
| escapeAttribute | string | 'data-toggle-escape' | Per-trigger Escape setting: present (or "true") closes on Escape, "false" never does; it wins over escape |
Instance Methods:
| Method | Description |
|--------|-------------|
| destroy() | Remove all event listeners for this instance |
| toggle(className, elementSelector?, force?) | Programmatically toggle a class; force true adds, false removes (no event when nothing changes) |
| isActive(className, elementSelector?) | Check if a class is currently active |
| refresh() | Re-scan DOM for new toggle elements |
Custom Events
The library dispatches datatoggle events with the following detail:
{
classNames: string[]; // Array of toggled class names
target: Element; // Element that received the class
trigger: Element | null; // Element that was clicked, or whose classes Escape closed (null for toggle())
active: boolean; // Whether classes were added (true) or removed (false)
source: 'click' | 'api' | 'escape'; // What changed them
}Browser Support
Works in all modern browsers that support:
- ES6+ features
classListAPICustomEventWeakMap
Use Cases
- 🌙 Dark/light mode toggles
- 📱 Mobile navigation menus
- 🗂️ Sidebar panels
- 🪟 Modal dialogs
- 📖 Accordion/collapsible content
- 🎛️ Settings panels
- 🔍 Search overlays
- 🎨 Theme switchers
Development
# Install dependencies
pnpm install
# Run tests
pnpm test
# Build the package
pnpm run build
# Type-check src and tests
pnpm typecheck
# Run tests in watch mode
pnpm run test:watchRelease
Releases are published to npm by .github/workflows/publish.yml with npm trusted publishing (OIDC): no npm token is stored anywhere.
Publish a GitHub release with a tag like v1.2.3. The workflow runs the tests, builds, sets package.json to that version, commits the build back to main and publishes to npm. The trusted publisher on npmjs.com names the workflow publish.yml.
License
MIT © phucbm
