Reputation: 21893
$(".timeSeenInput").on("focusout keypress",function(event){
alert($(this).attr("id"))
})
I need to detect when the user tabs away from an input box or when pressing away from it. the code above fires twice for when I press a key. how do I make it either fire for either tab or focusout but not both?
Upvotes: 0
Views: 158
Reputation: 74420
You could debounce it a little:
(function () {
var timeout;
$(".timeSeenInput").on("focusout keypress", function (event) {
if (!timeout) {
var self = this;
timeout = setTimeout(function () {
console.log(self.id);
timeout = null;
}, 0);
}
})
})();
Upvotes: 1
Reputation: 74738
This will only fire when tab key
is pressed and focusout
is happened:
$(".timeSeenInput").on("focusout keydown", function (e) {
var kc = e.which || e.keyCode;
if (kc === 9) {
alert('focusout with tab only');
}
});
Upvotes: 0
Reputation: 13567
This is what the blur
event is for.
Fiddle: http://jsfiddle.net/DPh6P/
$(".timeSeenInput").on("blur", function (event) {
alert($(this).attr("id"))
})
Upvotes: 0
Reputation: 34895
Tabbing out is produced by both events. You can flag your tabbing out event and not handle the blur:
var handleBlur = true;
$(".timeSeenInput").on("focusout keypress",function(event) {
if (event.type === 'keypress' && event.keyCode === TAB) {
alert($(this).attr("id"));
handleBlur = false;
return;
} else if (event.type === 'blur' && handleBlur) {
// Handle blur
}
handleBlur = true;
});
Upvotes: 0