.keydown( handler(eventObject) ) Returns: jQuery

Description: Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.

  • version added: 1.0.keydown( handler(eventObject) )

    handler(eventObject)A function to execute each time the event is triggered.

  • version added: 1.0.keydown()

This method is a shortcut for .bind('keydown', handler) in the first variation, and .trigger('keydown') in the second.

The keydown event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

For example, consider the HTML:

  <input id="target" type="text" value="Hello there" />
<div id="other">
  Trigger the handler

The event handler can be bound to the input field:

$('#target').keydown(function() {
  alert('Handler for .keydown() called.');

Now when the insertion point is inside the field and a key is pressed, the alert is displayed:

Handler for .keydown() called.

We can trigger the event manually when another element is clicked:

$('#other').click(function() {

After this code executes, clicks on Trigger the handler will also alert the message.

If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the document object. Because of event bubbling, all key presses will make their way up the DOM to the document object unless explicitly stopped.

To determine which key was pressed, we can examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the .which property so we can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, .keypress() may be a better choice.


Show the event object for the keydown handler when a key is pressed in the input.

<!DOCTYPE html>
fieldset { margin-bottom: 1em; }
input { display: block; margin-bottom: .25em; }
#print-output {
  width: 100%;
.print-output-line {
  white-space: pre;
  padding: 5px;
  font-family: monaco, monospace;
  font-size: .7em;

  <script src="http://code.jquery.com/jquery-latest.js"></script>
    <label for="target">Type Something:</label>
    <input id="target" type="text" />
<button id="other">
  Trigger the handler
<script type="text/javascript" src="/scripts/events.js"></script>
var xTriggered = 0;
$('#target').keydown(function(event) {
  if (event.keyCode == '13') {
   var msg = 'Handler for .keydown() called ' + xTriggered + ' time(s).';
  $.print(msg, 'html');

$('#other').click(function() {