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();
source share