1

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.

user1082764
  • 1,973
  • 9
  • 26
  • 40

3 Answers3

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
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

Community
  • 1
  • 1
xkickflip
  • 768
  • 6
  • 17
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