Search code examples
jquerykeypressjquery-events

Best way of capturing key press events


I would like to capture key press events on the browser with jQuery.

My current jQuery version is 1.9.1

There are so many solutions but what is the best and latest version which would cover majority of the browsers

Also it need to fire each time key pressed no matter what

It has to be document level. I mean while browser is open at which ever location hits a key.


Solution

  • This is the most explanatory example Check this out

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>keypress demo</title>
      <style>
      fieldset {
        margin-bottom: 1em;
      }
      input {
        display: block;
        margin-bottom: .25em;
      }
      #print-output {
        width: 100%;
      }
      .print-output-line {
        white-space: pre;
        padding: 5px;
        font-family: monaco, monospace;
        font-size: .7em;
      }
      </style>
      <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    </head>
    <body>
    
    <form>
      <fieldset>
        <label for="target">Type Something:</label>
        <input id="target" type="text">
      </fieldset>
    </form>
    <button id="other">
      Trigger the handler
    </button>
    <script src="/resources/events.js"></script>
    
    <script>
    var xTriggered = 0;
    $( "#target" ).keypress(function( event ) {
      if ( event.which == 13 ) {
         event.preventDefault();
      }
      xTriggered++;
      var msg = "Handler for .keypress() called " + xTriggered + " time(s).";
      $.print( msg, "html" );
      $.print( event );
    });
    
    $( "#other" ).click(function() {
      $( "#target" ).keypress();
    });
    </script>
    
    </body>
    </html>