jQuery and Keypresses

jQuery and Keypresses
0.0 0

#1

Is it possible in jQuery to make a specific action happen when I press a specific key, if so how?

Example: User presses A, alert says “You pressed the A key”.


#2
$("body").keypress(function(e){
  alert(`You pressed the ${String.fromCharCode(e.charCode)} key`);
});

#3

You can use one of three methods based on your needs: .keypress(), .keydown(), .keyup().

.keydown will register an event when the key is pressed
.keyup will register an event when the key is released
.keypress is almost identical to .keydown, except that it will not register an event for keys such as esc, shift, delete, etc.

As for the usage, see @BenGitter answer.