How to know the reason of blur?

To be able to handle the type of input from within the blur handler, you will need to use mousedown and keydown events instead. This is due to the order of events.

When you have a text input focused and you click elsewhere on the page, the order will be:

  • mousedown
  • input blur
  • mouseup
  • click

Similarly, with a tab, it is

  • keydown
  • input blur
  • keyup

You would need to store the "blur action" in an external variable so the blur handler can access it.

var _lastAction = "somethingelse";
$(document).bind("mousedown keydown", function () {
  //check keycode
  var e = window.event;
  var k = e ? event.keyCode : e.keyCode;
  if (k == 9) {
    //tab code
    _lastAction = "tab";
  } else if (e.type == "mousedown") {
    //click code
    _lastAction = "click";
  } else {
    _lastAction = "somethingelse";
  }
});

Then you can refer to the variable inside of your blur event handler.

I had to use this to maintain proper tabbing in a complicated dynamic form when pressing the tab. I had to check for click because trying to click/focus on a new spot in the form outside of tab order flow would still trigger the tab action, which would focus completely on the wrong element from what you were trying to click on.


If you are trying to do two different things depending on which method was used, bind handlers to listen for .click() and .keyup(), then check for the keycode

var k = (window.event) ? event.keyCode : e.keyCode;

Or something on the order of this if you need

$(document).bind("click keyup", function(){
   //check keycode
   var e = (window.event);
   var k = (e)?event.keyCode:e.keyCode;
   if(k==9){
      //tab code
   }else if(e.type=='click'){
      //click code
   }

});