Set the input focus of the field to the beginning of input

I am looking for a way to start typing on a website without selecting anything and then focus on a specific input field.

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

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

Great importance.

+4
source share
4 answers

You must bind the keydown event, but immediately unbind it so that you can print in other text inputs without returning focus to the default input.

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

See an example here.

+6
source

There is no problem with @mVChr solution in this solution: I.e. you can click on another input with the mouse and start typing without losing focus due to keydown binding.

Also, this solution does not remove all keydown bindings elements, but instead uses a named handler.

 var default_input_handler = function() { $('.default-input').focus(); $(document).off('keydown', default_input_handler); } $(document).on('keydown', default_input_handler); $('input, textarea, select').on('focus', function() { $(document).off('keydown', default_input_handler); }); 
+1
source

If you plan to do this, I would say that instead of onKeyDown use onKeyUp. This is much earlier in action, which would facilitate the flow of interaction.

0
source

The answer is simple like this:

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

keydown is preferable because keyup only starts after pressing the first key - and therefore does not capture the first key entered in the search field.

0
source

Source: https://habr.com/ru/post/1337624/


All Articles