I created a newer version of trackFocus that includes more generic event detection (including touch and pointer), only adds a single attribute to the body instead of littering the DOM with classes and exposes a small API for scripting. Check out What Input?.
Track Focus
trackFocus adds a class to elements when they receive focus, allowing specific styling for keyboard versus mouse interaction.
Check out the demo page.
How it works
- Watches the body for the
mousedown
and keydown
events and stores as a variable.
- Watches the body for the
focusin
event and applies the correct class based on whether the previous event was from the mouse or keyboard.
- Watches the body for the
focusout
event and removes the mouse/keyboard class.
- Style the focus state as needed.
Usage
- Include trackFocus.min.js (just 500 bytes).
- Style focus states.
Compatibility
Works as-is in all modern browsers. For older browsers, like IE8, grab these polyfills: