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:
1 2 3 4 5 6 7 8 9 |
$('#detect').on('focus', function(e){ $(window).keyup(function (e) { var code = (e.keyCode ? e.keyCode : e.which); if (code == 9) { // if the tab key was pushed do the following alert('I was tabbed!'); } }); }); |
Reference: http://jsfiddle.net/LPGLm/1/
To edit the change listener:
1 2 3 4 5 6 7 |
$(window).keyup(function (e) { var code = (e.keyCode ? e.keyCode : e.which); if (code == 9 && $('#detect:focus').length) { // if focus is detected do the following alert('I was tabbed!'); } }); |
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