Simulate the ontype event

I want to simulate the effect of Google Search, even if the search box is not focused, the user can start typing, and the input field will capture all the strokes of the keyboard.

I was looking for the ontype event but didn't find anything. I know that the event object in callbacks for events like click has keyboard information, but I don't think this is what I need.

+4
source share
4 answers

This task:

  $(document).on('keydown', function() { $('input').focus(); }); 
+4
source

HTML:

 <input type="text" id="txtSearch" /> 

JavaScript:

 var googleLikeKeyCapture = { inputField : null, documentKeydown: function(event) { var inputField = googleLikeKeyCapture.inputField; if(event.target != inputField.get(0)) { event.target = inputField.get(0); inputField.focus(); } }, init: function() { googleLikeKeyCapture.inputField = $('#txtSearch'); $(document).bind('keydown', googleLikeKeyCapture.documentKeydown); googleLikeKeyCapture.inputField .focus(function() { $(document).unbind('keydown'); }) .blur(function() { $(document).bind('keydown', googleLikeKeyCapture.documentKeydown); }); googleLikeKeyCapture.init = function() {}; } }; $(googleLikeKeyCapture.init); 

You can also find jsFiddle example here

EDIT:

And now it is a jQuery plugin . :) If keydown occurs in a text field or input field, it does not capture keys, everything else goes to the specified input field. If your selector matches more than one element, it uses only the first element.

Usage: $('#txtSearch').captureKeys();

+3
source

The event you are running is onkeypress .

+2
source
0
source

All Articles