How can I know which event caused a blur event in jQuery?
Blur event triggered using click or tab
etc. How can I know this blur event is due to click or tab
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
}
});
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 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 the wrong element from what you were trying to click on.