inputModality()
Detect keyboard, mouse or touch input.
Try the example
Click or tap the sample button, then press Tab. The input card reflects the latest input type. Use this to adapt focus presentation without hiding useful feedback.
Click, tap or press a key.
Add it to your project
- Copy the HTML. Place the markup inside the component where this behavior belongs. The preview’s visual classes are website styles; use your own design system.
- Connect the behavior. Copy the JavaScript tab and call its exported
mount(element)after your component’s elements exist. Replace simulated delays and data operations with your own application code. - Clean up. Call the returned cleanup when the component unmounts. It aborts the example’s listeners and releases the helper’s timers, observers or state.
API and lifecycle
Create one tracker with an optional onChange callback. current begins as unknown, then reflects the last meaningful keyboard or pointer input. This describes the last interaction, not the visitor's device type.
- Interface
onChange; current, destroy- Lifecycle
- Read current when needed. destroy() removes its captured pointerdown and keydown listeners; avoid creating a tracker for every button.
Accessibility and safety
Implementation notes
Initialize after the DOM is available. Keep native controls and keyboard interactions intact; release listeners and timers on unmount.
Prefer :focus-visible for focus rings. Do not hide essential controls or keyboard feedback based on an assumed input device.
What to check
Switch between keyboard, mouse and touch. Confirm focus remains visible when navigating with Tab and controls still work after switching methods.