Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  67] [ 4]  / answers: 1 / hits: 66138  / 11 Years ago, mon, april 22, 2013, 12:00:00

I want to detect the focus event of an element, but only if it was initiated by the user pressing the tab key. For example:



<input type=text id=foo />
<input type=text id=detect />


If the user is focused on #foo and presses Tab, I want the event to fire once #detect becomes focused (or a conditional inside the focus event to be true). Conversely, if the user simply clicks on the #detect field to focus it, I do not want the event to fire (or I want the conditional inside the focus event call to be false).



I don't want to use the keydown event of #foo and check if the tab key was pressed, as I want the approach to be independent of any other element.



I looked through the console output of the following code, but couldn't notice any real differences between the two methods of focusing:



$('#detect').on('focus', function(e){
console.log(e);
});


(fiddle)



Is this possible to accomplish in a relatively simple way?


More From » jquery

 Answers
110

I know you have accepted an answer but you could test the button pressed using the following:



$('#detect').on('focus', function(e){
$(window).keyup(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
alert('I was tabbed!');
}
});
});


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



Edit: change the listener around:



$(window).keyup(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9 && $('#detect:focus').length) {
alert('I was tabbed!');
}
});


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


[#78729] Saturday, April 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arthur

Total Points: 729
Total Questions: 107
Total Answers: 109

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;