最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Simulate an "ontype" event - Stack Overflow

programmeradmin2浏览0评论

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

I have looked for an ontype event, but haven't found 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'm after.

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

I have looked for an ontype event, but haven't found 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'm after.

Share Improve this question asked Oct 22, 2011 at 14:03 RandomblueRandomblue 116k150 gold badges362 silver badges557 bronze badges 4
  • 1 how about onkeypress or onkeyup – Rafay Commented Oct 22, 2011 at 14:05
  • Updated my answer. Apparently there is no need for catching character, changing target will do the magic. – Emre Erkan Commented Oct 22, 2011 at 14:42
  • Updated my answer again. :) I hope this time it's final. – Emre Erkan Commented Oct 22, 2011 at 15:08
  • You can accept your own answer too. But I appreciate if you accept mine :) – Emre Erkan Commented Oct 22, 2011 at 18:17
Add a ment  | 

4 Answers 4

Reset to default 5

This does the job:

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

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);

Also you can find jsFiddle example here

EDIT :

And now it's a jQuery plugin. :) If keydown occures in a textarea or input field it doesn't capture keys, anything else goes to designated input field. If your selector matches more than one element it only uses the first element.

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

The event you are after is onkeypress.

Try this jQuery Text Change Event plugin:

http://www.zurb./playground/jquery-text-change-custom-event

发布评论

评论列表(0)

  1. 暂无评论