Search code examples
jquerykeypress

Perform Action When Key is Pressed With Jquery?


I would like for an action to occur when I push the "1" key on my keyboard. My code below does not seem to work:

<script>
$(document).ready(function() {
    var code = e.keyCode || e.which;

    if (code == 97) {
        alert("hello world");
    }
});
</script>

Solution

  • Use keypress handler on document.

    DEMO

    $(document).ready(function() {
    
      $(document).on('keypress', function(e) {
        //            ^^^^^^^^
        var code = e.keyCode || e.which;
        if (code == 49) { // 1 is pressed
          alert("hello world!");
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
    <input type="text" />