Keyboard Events

Capture what users type with keydown, keyup, and keypress.

Syntax$(selector).on("keyup", function (e) { ... });

Keyboard events fire as the user types into a field or presses keys.

  • keydown — a key goes down.
  • keyup — a key is released (good for reading the final value).

The event object carries e.key (the character) and e.which (the key code).

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A search field triggers a live AJAX lookup on keyup so results update as the user types each character.
  • A code editor disables the Tab key's default focus-move behaviour and inserts spaces instead using keydown.
  • A game listens for arrow-key presses via keydown to move a player sprite on the canvas.

More examples

Show typed character on keyup

keyup fires after the key is released, so .val() returns the field content including the newest character.

Example · html
<input id="typebox" type="text" placeholder="Type here" />
<p>Value: <span id="display"></span></p>
<script>
$(function () {
  $("#typebox").on("keyup", function () {
    $("#display").text($(this).val());
  });
});
</script>

Detect Enter key on keydown

e.key gives the human-readable key name; checking for "Enter" handles the search-on-return pattern.

Example · html
<input id="search" type="text" placeholder="Search..." />
<p id="result"></p>
<script>
$(function () {
  $("#search").on("keydown", function (e) {
    if (e.key === "Enter") {
      $("#result").text("Searching for: " + $(this).val());
    }
  });
});
</script>

Intercept Tab key and insert spaces

e.preventDefault() blocks the default tab-focus behaviour, then two spaces are inserted at the cursor position.

Example · html
<textarea id="editor" rows="6" cols="40"></textarea>
<script>
$(function () {
  $("#editor").on("keydown", function (e) {
    if (e.key === "Tab") {
      e.preventDefault();
      var pos = this.selectionStart;
      var val = $(this).val();
      $(this).val(val.slice(0, pos) + "  " + val.slice(pos));
      this.selectionStart = this.selectionEnd = pos + 2;
    }
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.
Keyboard Events — jQuery | SoundsCode