jQuery: Focus input if not already focused
I want to focus an input field in the document's KeyDown event if it's not already focused. In case that it is already focused, nothing is supposed to happen. If it's not focused yet, the text content is to be deleted and the pressed key – if its char code is in a specific range – to be added.
My current code only works in the newest browsers, not even in Firefox 3.0 for example ...
$(document).keydown(function (e) {
var code = e.charCode ? e.charCode : e.keyCode ? 开发者_StackOverflowe.keyCode : 0;
if (code < 33 || code > 256) {
return;
}
// Check if the text input is focused
if ($("*:focus").attr("id") == "searchString") {
// Maybe more to come here ...
}
else {
// Clear content and focus
$("#searchString")
.val("")
.focus();
}
});
You can use document.activeElement
and check it's id
property, like this:
$(document).keydown(function (e) {
//e.which is normalized by jQuery already
if (e.which < 33 || e.which > 256) return;
if (document.activeElement && document.activeElement.id == "searchString") {
//do stuff
}
else {
$("#searchString").val("").focus();
}
});
Also you can switch to the event.which
property since it's already normalized by jQuery internally.
精彩评论