0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tony the Pony
  • 40,327
  • 71
  • 187
  • 281

2 Answers2

3

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 alt text

jQuery stopImmediatePropagation() documentation

Mike Grace
  • 16,636
  • 8
  • 59
  • 79
  • 2
    Won't the previously bound handlers already have run by the time this gets called? Also, I think you meant e.stopImmediatePropagation()... e.stopPropagation() prevents the event from bubbling up to parent elements, but I don't think it will prevent subsequent handlers on the same element from running. – Mike C Dec 01 '10 at 17:14
  • 1
    C, you were right. Thanks for catching that. My example had worked because I had used a live click handler to represent the third party code which binds at the document level instead of the element level. I have changed my answer to reflect this new knowledge. Thanks again for catching that and teaching me something new. – Mike Grace Dec 01 '10 at 20:01
2

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

Community
  • 1
  • 1
Mike C
  • 3,077
  • 22
  • 29