Search code examples
phpjavascriptjquerysearch-enginesetfocus

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.


Solution

  • 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.

    $(document).bind('keydown',function(e){
        $('#defaultInput').focus();
        $(document).unbind('keydown');
    });
    

    See example here.