Set input field focus on start typing

I am looking for a way to be able to start typing on a website without having selected anything and then have a specific input field in focus.

Google also employs this feature. In their search results you can click anywhere (defocus the search field) and when you start typing it automatically focuses on the search field again.

I was thinking about jQuery general onkeyup function to focus on the field, any suggestions?

Much appreciated.



You should bind the keydown event, but unbind it immediately so that typing may continue in other text inputs without reverting focus to the default input.


See example here.


This solution does not have the problem that @mVChr's solution has: Ie you can click on another input with the mouse and start typing without losing focus due to the keydown-binding.

Also this solution does not remove all the element's keydown-bindings, but uses a named handler instead.

var default_input_handler = function() {
    $(document).off('keydown', default_input_handler);

$(document).on('keydown', default_input_handler);

$('input, textarea, select').on('focus', function() {
    $(document).off('keydown', default_input_handler);

If planning to do this I'd say use onKeyUp instead of onKeyDown. Its much earlier in the action which would help ease the flow of the interaction.


The answer is as simple as this:

$(document).keydown(function() { $('#element').focus(); });

keydown is preferred after all because keyup will only be fired after the first key is pressed - and respectively not capture the first key typed in my search field.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.