Search code examples
htmljqueryinputjquery-eventsonkeydown

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?


Solution

  • 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