jQuery Keyboard Events

Keyboard events fire when a user presses, holds, or releases a key on the keyboard. jQuery makes it easy to detect these actions and respond to them — whether you want to validate input as the user types, create shortcuts, or build interactive text tools.

Three Keyboard Events in jQuery

EventFires WhenDetects Character?
keydown()Key is pressed downNo (key code only)
keypress()Key is pressed and a character is producedYes (character code)
keyup()Key is releasedNo (key code only)

Diagram: Keyboard Event Order

  User presses the "A" key:

  ┌──────────────┐
  │  Key goes    │  → keydown  fires first
  │  down        │
  └──────────────┘
         │
  ┌──────────────┐
  │  Character   │  → keypress fires (produces "a" or "A")
  │  is made     │
  └──────────────┘
         │
  ┌──────────────┐
  │  Key comes   │  → keyup   fires last
  │  up          │
  └──────────────┘

keydown() — Detect Key Press

The keydown() event fires the moment a key is pushed down. It fires for every key — letters, numbers, arrows, function keys, Shift, Ctrl, and so on.

$(document).ready(function() {
    $(document).keydown(function(event) {
        console.log("Key pressed: " + event.key);
        console.log("Key code: " + event.keyCode);
    });
});

keyup() — Detect Key Release

The keyup() event is best for reading what the user typed, because by the time it fires, the character is already inside the input field.

$(document).ready(function() {
    $("#searchBox").keyup(function() {
        var typed = $(this).val();
        $("#livePreview").text("You typed: " + typed);
    });
});

This creates a live preview of whatever the user types in the search box.

Counting Characters in Real Time

HTML:
<textarea id="message" maxlength="150"></textarea>
<p>Characters left: <span id="counter">150</span></p>

jQuery:
$(document).ready(function() {
    $("#message").keyup(function() {
        var remaining = 150 - $(this).val().length;
        $("#counter").text(remaining);
    });
});

Diagram: Live Character Counter

  User types "Hello"  → 5 characters used
                      → Counter shows: 145 left

  User types " World" → 11 characters used
                      → Counter shows: 139 left

  [textarea]          [Characters left: 139]

Detecting Specific Keys — event.key and event.keyCode

The event object carries information about which key was pressed. Use event.key for modern code and event.keyCode for older browser support.

$(document).ready(function() {
    $(document).keydown(function(event) {
        if (event.key === "Escape") {
            $("#modal").hide();
        }

        if (event.key === "Enter") {
            $("#searchForm").submit();
        }
    });
});

Common Key Codes

  Enter     → keyCode 13
  Escape    → keyCode 27
  Space     → keyCode 32
  Left Arrow  → keyCode 37
  Up Arrow    → keyCode 38
  Right Arrow → keyCode 39
  Down Arrow  → keyCode 40
  A           → keyCode 65
  Z           → keyCode 90
  0           → keyCode 48
  9           → keyCode 57

Arrow Key Navigation Example

$(document).ready(function() {
    var position = 0;

    $(document).keydown(function(event) {
        if (event.keyCode === 39) {   // Right arrow
            position += 10;
        }
        if (event.keyCode === 37) {   // Left arrow
            position -= 10;
        }
        $("#box").css("left", position + "px");
    });
});

Press the right or left arrow keys to move a box across the screen.

keypress() — For Printable Characters Only

The keypress() event does not fire for non-printable keys like Escape, Delete, or arrow keys. It fires only when a key produces a visible character.

$(document).ready(function() {
    $("#numberOnly").keypress(function(event) {
        var charCode = event.which;
        if (charCode < 48 || charCode > 57) {
            event.preventDefault();   // Block non-numeric input
        }
    });
});

This forces a text field to accept only digit characters (0–9).

Attaching Events to Specific Elements vs document

// Listens to keys only when the input is focused
$("#searchBox").keyup(function() { ... });

// Listens to keys anywhere on the page
$(document).keydown(function() { ... });

Practical: Search with Enter Key

$(document).ready(function() {
    $("#searchInput").keydown(function(event) {
        if (event.key === "Enter") {
            var query = $(this).val();
            $("#results").text("Searching for: " + query);
        }
    });
});

Quick Summary

  • keydown() fires when a key goes down — works for all keys.
  • keyup() fires when a key is released — best for reading typed input.
  • keypress() fires only for printable characters — not arrows or function keys.
  • Use event.key to detect specific keys like "Enter", "Escape", "ArrowLeft".
  • Use event.preventDefault() to block unwanted key inputs.

Leave a Comment

Your email address will not be published. Required fields are marked *