A key's default action is performed during the keydown
event, so, naturally, by the time keyup
propagates, the Tab key has changed the focus to the next field.
You can use:
jQuery(document).ready(function() {
$('#firstfield, #secondfield').on({
"keydown": function(e) {
if (e.which == 9) {
alert("TAB key for " + $(this).attr("id") + " .keydown() called.");
}
},
"keyup": function(e) {
if (e.which != 9) {
alert("Handler for " + $(this).attr("id") + " .keyup() called.");
}
}
});
});
This way, if the Tab key is pressed, you can make any necessary adjustments before handling other keys. See your updated fiddle for an exampe.
Edit
Based on your comment, I revamped the function. The JavaScript ended up being a bit complicated, but I'll do my best to explain. Follow along with the new demo here.
jQuery(document).ready(function() {
(function($) {
$.fn.keyAction = function(theKey) {
return this.each(function() {
if ($(this).hasClass("captureKeys")) {
alert("Handler for " + $(this).attr("id") + " .keyup() called with key "+ theKey + ".");
// KeyCode dependent statements go here.
}
});
};
})(jQuery);
$(".captureKeys").on("keydown", function(e) {
$("*").removeClass("focus");
$(this).addClass("focus");
});
$("body").on("keyup", "*:focus", function(e) {
if (e.which == 9) {
$(".focus.captureKeys").keyAction(e.which);
$("*").removeClass("focus");
}
else {
$(this).keyAction(e.which);
}
});
});
Basically, you give class="captureKeys"
to any elements on which you want to monitor keypresses. Look at that second function first: When keydown
is fired on one of your captureKeys
elements, it's given a dummy class called focus
. This is just to keep track of the most recent element to have the focus (I've given .focus
a background in the demo as a visual aid). So, no matter what key is pressed, the current element it's pressed over is given the .focus
class, as long as it also has .captureKeys
.
Next, when keyup
is fired anywhere (not just on .captureKeys
elements), the function checks to see if it was a tab. If it was, then the focus has already moved on, and the custom .keyAction()
function is called on whichever element was the last one to have focus (.focus
). If it wasn't a tab, then .keyAction()
is called on the current element (but, again, only if it has .captureKeys
).
This should achieve the effect you want. You can use the variable theKey
in the keyAction()
function to keep track of which key was pressed, and act accordingly.
One main caveat to this: if a .captureKeys
element is the last element in the DOM, pressing Tab will remove the focus from the document in most browsers, and the keyup
event will never fire. This is why I added the dummy link at the bottom of the demo.
This provides a basic framework, so it's up to you to modify it to suit your needs. Hope it helps.