Execute a script when a user is pressing a key in HTML?

The onkeydown attribute in HTML triggers when a user presses a key down. This event fires immediately when a key is pressed, before the key is released. It is commonly used for real-time keyboard interaction, game controls, and form validation.

Syntax

Following is the syntax for the onkeydown attribute −

<element onkeydown="function()"></element>

The function() represents the JavaScript function to execute when the key is pressed down.

Basic Key Press Detection

Example

Following example demonstrates basic key press detection using the onkeydown attribute −

<!DOCTYPE html>
<html>
<head>
   <title>Basic Key Press Detection</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <p>Press a key inside the textbox:</p>
   <input type="text" onkeydown="display()" style="padding: 8px; font-size: 16px;">
   <script>
      function display() {
         alert("You pressed a key!");
      }
   </script>
</body>
</html>

When you press any key inside the text input, an alert box appears with the message "You pressed a key!" −

Input field displayed with alert showing: "You pressed a key!"

Detecting Specific Keys

You can identify which specific key was pressed using the event.key property or event.keyCode property. The event.key returns the actual key value, while event.keyCode returns the numeric code.

Example − Identifying Specific Keys

<!DOCTYPE html>
<html>
<head>
   <title>Specific Key Detection</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <p>Press different keys and see which key you pressed:</p>
   <input type="text" onkeydown="showKey(event)" style="padding: 8px; font-size: 16px;">
   <p id="output" style="color: blue; font-weight: bold;">Key pressed: None</p>
   <script>
      function showKey(event) {
         document.getElementById("output").innerHTML = "Key pressed: " + event.key + " (Code: " + event.keyCode + ")";
      }
   </script>
</body>
</html>

This example displays the actual key and its numeric code when pressed −

Input field with output showing: "Key pressed: a (Code: 65)" when 'a' is pressed

Key Event Properties

The key event object provides several useful properties for handling different key combinations −

  • event.key − Returns the actual key value (e.g., "a", "Enter", "Space")

  • event.keyCode − Returns the numeric key code

  • event.ctrlKey − Returns true if Ctrl key is pressed

  • event.shiftKey − Returns true if Shift key is pressed

  • event.altKey − Returns true if Alt key is pressed

Example − Detecting Key Combinations

<!DOCTYPE html>
<html>
<head>
   <title>Key Combinations</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <p>Try key combinations like Ctrl+A, Shift+B, Alt+C:</p>
   <input type="text" onkeydown="checkCombination(event)" style="padding: 8px; font-size: 16px;">
   <p id="combo-output" style="color: green; font-weight: bold;">Press keys to see combinations</p>
   <script>
      function checkCombination(event) {
         var message = "Key: " + event.key;
         if (event.ctrlKey) message += " + Ctrl";
         if (event.shiftKey) message += " + Shift";
         if (event.altKey) message += " + Alt";
         document.getElementById("combo-output").innerHTML = message;
      }
   </script>
</body>
</html>

This example detects and displays key combinations when multiple keys are pressed together −

Output showing: "Key: a + Ctrl + Shift" when Ctrl+Shift+A is pressed
Key Event Flow Key Down Key Press Key Up onkeydown onkeypress onkeyup Complete keyboard interaction sequence

Different Key Events

HTML provides three main keyboard events that trigger at different stages of key interaction −

Event When it Triggers Use Case
onkeydown When key is first pressed down Real-time detection, game controls
onkeypress When key produces a character output Character input validation
onkeyup When key is released Action completion, toggle effects

Example − Comparing Key Events

<!DOCTYPE html>
<html>
<head>
   <title>Key Events Comparison</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <p>Type in the input field and observe different events:</p>
   <input type="text" 
          onkeydown="logEvent('keydown')" 
          onkeypress="logEvent('keypress')" 
          onkeyup="logEvent('keyup')" 
          style="padding: 8px; font-size: 16px;">
   <div id="event-log" style="border: 1px solid #ccc; padding: 10px; height: 100px; overflow-y: auto; margin-top: 10px;">Event log will appear here...</div>
   <script>
      function logEvent(eventType) {
         var log = document.getElementById("event-log");
         log.innerHTML += eventType + " triggered<br>";
         log.scrollTop = log.scrollHeight;
      }
   </script>
</body>
</html>

This example logs all three key events to show their sequence when a key is pressed −

Event log showing:
keydown triggered
keypress triggered
keyup triggered

Conclusion

The onkeydown attribute provides immediate response to key presses and is ideal for real-time applications. It works with all keys including special keys like arrows, function keys, and modifier keys. For complete keyboard handling, consider using onkeydown, onkeypress, and onkeyup events together based on your specific requirements.

Updated on: 2026-03-16T21:38:53+05:30

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements