开发者

How to hook a keyboard event handler onto an INPUT element with jQuery?

I want to attach my own key event handler to an INPUT that already has another event handler attached to onkeydown. Essentially, I want to receive a key event before all the other handlers and check if the user pressed a certain key 开发者_如何学编程-- if yes, I want to perform some functions and discard the event, if no, I want to pass it along to the other handler(s).

How can I do this with jQuery?


If you are loading a 3rd party script or jQuery addon you can just load your script or function first. If you do that then you can use something like this without the mess of unbinding and rebinding event handlers.

// your possible interceptor code
$("#awesome").keydown(function(e) {
  if (e.keyCode < 70) {
    e.stopImmediatePropagation();
    console.log("BLOCKED!!!");
  };
});

// possible 3rd party event code loaded after your code
$("#awesome").keydown(function(e) {
  console.log("3rd party:"+e.keyCode);
});

Example webpage => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-key-event-interception.html

Example output of Firebug console

How to hook a keyboard event handler onto an INPUT element with jQuery?

jQuery stopImmediatePropagation() documentation


According to the jQuery bind() documentation:

"When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound."

So it looks like you will have to unbind the other handlers, bind yours and then add the others back if you want yours to run first.

There is some good information in this thread with respect to that: jQuery: Unbind event handlers to bind them again later

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜