JS to listen for tab focus on an html element

Want to detect focus initiated by a user pressing the tab key button on their keyboard? If the user focuses on an element by pressing tab, you can then fire many different types of commands (alert, console log, toggle class, add or remove class, hide, etc). You can also change out the code for “tab” to listen for any key commands (ie: hold shift + tab). The code snippet’s interaction will have no impact on mouse users and users who are on a mobile device.

If you simply want to detect if the tab button was pressed, you can use the following code:


Reference: http://jsfiddle.net/LPGLm/1/

To edit the change listener:


Swap out #detect for the element you are listening for.

References: http://jsfiddle.net/LPGLm/7/

Accessibility benefits

This code snippet can be useful to let sighted keyboard-only and assistive technology users navigate easier. This snippet can assist in allowing you to use JavaScript to listen for tab focus on an html element. If focus is detected, you can add actions to allow users to explicitly access buttons, panels or other information that is not otherwise accessible.

Article reference: Stack Overflow