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?.
trackFocus adds a class to elements when they receive focus, allowing specific styling for keyboard versus mouse interaction.
Check out the demo page.
- Watches the body for the
mousedown
andkeydown
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.
- Include trackFocus.min.js (just 500 bytes).
- Style focus states.
Works as-is in all modern browsers. For older browsers, like IE8, grab these polyfills:
- classList by remy
- EventListener by jonathantneal
- focusin by Yaffle
- Or use the bundled, minified version.