Embarking on your JavaScript journey? One crucial aspect to grasp is keyboard events. On this page, we'll dive into the world of W3Schools, exploring how to capture and manipulate keyboard events using JavaScript. Let's start by understanding the basics.
Keyboard events are indispensable in interactive web development. They make web applications respond to user keystrokes, enabling functionalities like form entry, editing text, and using shortcuts. Let's dive into how W3Schools helps us tap into this power.
The W3Schools Boilerplate & Event Handlers

Before we break into code, let's ensure we're set up. W3Schools provides a standard script tag and a </sample> tag for testing. This is where our JavaScript magic will take place.
In JavaScript, we use event handlers to capture user interactions. The 'onkeydown', 'onkeyup', and 'onkeypress' properties trigger when a key is pressed, released, or during press. Let's explore each.
onkeydown Event

The 'onkeydown' event fires as soon as a key is pressed, even before the key is released. It's often used to implement continuous actions like character-by-character typing or gaming mechanics.
Example: To display the ASCII value of a pressed key, use 'event.keyCode'.onkeydown="displayASCII(event)"
| <p id="demo"></p> | <script> function displayASCII(e) { let x = e.keyCode; document.getElementById("demo").innerHTML = "ASCII Value: " + x; } </script> |
onkeyup Event

The 'onkeyup' event fires as soon as a key is released. It's perfect for validating user input, e.g., preventing insertion of invalid characters.
Example: Limiting user input to numbers only.
onkeyup="validateNum()"
Key Press Combinations & Codes
Some keyboard events require combinations or specific key codes. W3Schools offers a comprehensive list of key codes. Let's explore a few.
For combinations, use the `event.ctrlKey`, `event.altKey`, and `event.shiftKey` properties. For code-specific keys like Enter, Escape, etc., refer to the W3Schools list.
Special Keys

Some keys have unique properties. The 'Backspace' key, for instance, is represented by the key code 8.
Example: Displaying an alert when the 'Backspace' key is pressed.
onkeydown="if(event.keyCode == 8) alert('Backspace pressed!');"
Key Combinations
Some functionalities require key combinations, e.g., Ctrl + C. To detect these, use the event properties mentioned above.
Example: Displaying an alert when Ctrl + C is pressed.
onkeydown="if(event.ctrlKey && event.keyCode == 67) alert('Ctrl + C pressed!');"
Mastering keyboard events at W3Schools empowers you to build responsive, interactive web applications. Keep practicing, keep exploring, and happy coding!





















