Reputation: 1736
I want to catch all key presses on my webpage so that when you start typing the text appears in the search box (input) and this box gets focus.
Can someone provide me some hints?
Upvotes: 2
Views: 1739
Reputation: 12358
I wanted to implement this feature on my website, but only when the user presses s
(s for search) and I didn't want it to trigger if the focus was already in another input box. Here's my solution:
$(document).on("keyup", function(e) {
// :input applies to input, select, textarea, etc.
if (!$(':input').is(":focus")) {
if (!$('input[name=query]').is(":focus")) {
var key = e.keyCode || e.which;
if (key == 83) { // if 's'
$('input[name=query]').focus();
}
}
}
});
Credit to @Wolle whose answer I used to get started.
Upvotes: 1
Reputation: 10242
Solution
Since you tagged your question with jquery
, here you go:
var $search = $("#search");
$(document).on("keydown", function(e) {
if (!$search.is(":focus"))
if (e.which != 9 && e.which != 13)
$search.focus();
});
The .focus()
function to set the focus to the input field won't be called if the focus is already set. The input field also won't be selected if the user pressed the tab
or enter
key!
Accessibility
If someone tries to use your website without a mouse (just with keyboard), he won't be able to navigate anywhere. Maybe you have to consider to use additional techniques like the HTML's tabindex.
Upvotes: 5
Reputation: 3867
You can use jquery like below
$(document).keydown(function(event) {
$("id-of-input-box").focus()
});
Upvotes: 1