Simplest way to detect keypresses in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

The easiest way to detect keypresses in JavaScript, use the onKeyPress event handler −

document.onkeypress

The key press is matched with the keyCode property, which returns the Unicode character code of the key that triggered the onkeypress event.

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=
1.0">
<title>Document</title>
</head>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<script>
   document.onkeypress = function (eventKeyName) {
      eventKeyName = eventKeyName || window.event;
      if(eventKeyName.keyCode==13){
         console.log('You have pressed enter key');
      } else {
         alert(String.fromCharCode(eventKeyName.keyCode))
   }
};
</script>
</body>
</html>

To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.

Output

This will produce the following output −

Case 1 − On pressing ENTER key, you will get the following output on console.

Case 2 − When you press any other key except ENTER, example letter g, then the same would be visible on console −


raja
Published on 01-Sep-2020 11:40:27
Advertisements