Detect if focus is due to a keystroke or click

I am currently using focus on a specific form element to know when the user has a tab or clicked on another field.

I need to know this because starting an ajax call right after that fills in several different fields (for example, enter a valid zip code, it searches for db and returns with the city).

Now, my question is, the ajax call gets an html response and upon loading it causes the form to lose its current focus.

I need a way to keep this focus and restore it after ajax call.

So far, I got navigation to some kind of work. This breaks down a lot, and also interferes with loading other things on the page (like dialog boxes). So, I believe that there should be a better way to do this, so I am here. Let me know if you need more information. The code is below.

All the best!

    $('.DZipCode').focusout(function () {
      var ZipCode = $('.DZipCode').val();


    $.ajax({ // create an AJAX call...
        async: false,
        type: "POST", // GET or POST
        url: "/Home/SelectZipCodeDataDestination", // the file to call`
        data: { zipCode: ZipCode },
        success: function (response) { // on success.. 
            $(":input").focus(function() {
                var prevFocus;

                prevFocus = $(this).attr("id");
               $('#quotetab').html(response);
                $('#'+prevFocus).focus();
           // });               
        }  // end of success
    });  // end of .ajax

});

+5
source share
1 answer

The easiest way I can come up with is to set a flag when a key is pressed, and then just check the flag when you need to know.

var tabPressed = false;

$('input[type="text"], textarea')
    .keydown(function(e) { 
        var keyCode = e.keyCode || e.which; 

        tabPressed = (keyCode==9) ? true : false;
    })
    .focus(function() {
        tabPressed = false;
    });

Then you can do

if(tabPressed) {
//some stuff
}

in your ajax success callback (or anywhere).

+6
source

All Articles