I have a few input fields one on top of each other, I want to be able to check if a user used the tab key or clicked to focus on the current input field.
Checking on the .live('click', function() {
is easy but i don't know how to check if they used tab to focus on the current input field.
Asked
Active
Viewed 2,571 times
1

user1082764
- 1,973
- 9
- 26
- 40
3 Answers
6
Iām sure there are many ways to do this, but one way is to listen for the keyup
event and then find out what element is focused, if any:
$(document).on('keyup', function(e) {
if(e.keyCode == 9) {
var input = $(this).find('input:focus');
// input is the element that has focus after the tab key was pressed
}
});
This might not be a guarantee that the tab
key was used to bring focus to the element, but it might be sufficient for what you need.
If you want to check the event type that the user used before an input field gained focus, try:
$(document).on('keyup', function(e) {
if(e.keyCode == 9) {
findFocus(e);
}
}).on('click', 'input', findFocus);
function findFocus(e) {
var input = $(document).find('input:focus');
if ( input.length ) {
alert('Input was focused using '+e.type);
}
}
Also note that I used the .on()
event instead of .live()
, since live
is deprecated in 1.7.

David Hellsing
- 106,495
- 44
- 176
- 212
-
This is specifically what i needed. Thank you! ā user1082764 Mar 12 '12 at 04:05
1
Sounds like you want the "focus" event which will fire if the user clicks on OR tabs to the field
.on('focus', function() {});
also this answer notes that "live" is deprecated, use "on" instead https://stackoverflow.com/a/4944344/703173
-
no, i want to know if they pushed tab to focus on the input field. thanks for the input though ā user1082764 Mar 12 '12 at 03:55
-
0
$('input').on('click', function() {
$(this).data('clicked', true);
}).on('focus', function() {
setTimeout(function(){
if($(this).data('clicked') == true){
// clicked to focus
}else{
// used tab key to focus
}
$(this).data('clicked', false);
}, 100);
});

Malitta N
- 3,384
- 22
- 30