jQuery API

.keydown()

.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.4.3.keydown( [eventData], handler(eventObject) )

    eventDataA map of data that will be passed to the event handler.

    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 and second variations, and .trigger('keydown') in the third.

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:

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

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, pressing a key displays the alert:

Handler for .keydown() called.

To trigger the event manually, apply .keydown() without an argument:

$('#other').click(function() {
  $('#target').keydown();
});

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, 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 you 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.

Example:

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

<!DOCTYPE html>
<html>
<head>
  <style>
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;
}

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

$('#other').click(function() {
  $('#target').keydown();
});</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .keydown() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .keydown()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://mikefromindy.myopenid.com/ Mike Blandford

    Can the eventObject be documented here? I had to look at the examples to see the keyCode property: event.keyCode == '13'

  • Bob

    Is there a way to simulate a specific key pressed with the .keypress() function, instead of just triggering the keydown event?

  • daralthus

    Seems like Opera isn't supporting the event.preventDefault(); on the “tab” key. …good to know.

  • http://lovemeow.com Eric

    It would be nice if there was a helper function for onkeyEnter or onEnter this is what i bet most ppl are interested in when a keypress/down event happens.

  • http://herberthamaral.com/ Herberth Amaral

    That's a good question, but I'm afraid that's not possible. Not even with pure JavaScript event handling I was able to find something that could satisfy this need.

  • Anonymous

    So, when doing key combinations, like “Shift + Enter” do I need to store each chain of the combo (and maybe attach the keydown to the window object) and check for previous links the further I’m down the chain? Or am I missing a key utility, like isKeyDown?

  • david_king

    I’m trying to override the event object to contain data of my choosing so I can choose the value of “which”, but am having no luck so far…

  • http://www.learningjquery.com/ Karl Swedberg

    You would check for event.shiftKey:
    if ( event.which == 13 && event.shiftKey ) {
    // do something
    }

    check out the demo above for event properties that are available on keydown.

  • http://pulse.yahoo.com/_XUSAPGK4ZEU6KWG4NACF2WY7CI Joshua

    You cannot easily change values in the event object (probably for security reasons), but you might be able to copy and extend it:
    var faketab=$.extend({},event,{which:9, keyCode: 9};
    faketab.which == 9;

    However, a safer choice is to decouple your code:

    $('#target').keypress(function(event) {    fireWhich(event.which, event.ctrlKey, event.shiftKey);});


    So you can call fireWhich directly:
    fireWhich(13); //simulate Enter key
    fireWhich(9, false, true); //simulate SHIFT+TAB key

    This will not, however, make the focus go to the previous form item like a real SHIFT+TAB keystoke would do.

  • http://yogal.myopenid.com/ Szalski

    Wouldn't something like this work ?

    var event = $.Event('click');

    event.shiftKey = true;

    $('selector').trigger(event);

    I am using this to test my code based on specific interactions (fake). Should work with .which…

  • rajan

    i have a textarea that i add keydown event but this is not work in firefox.

  • http://twitter.com/legacye Addy Osmani

    Here's a very quick example I coded up where you can see textarea working fine with the keydown event in FireFox: http://jsfiddle.net/addyosmani/xEfSD/

  • Liel Dulev

    It seems that firefox 3.6 & chrome 6 (on mac OS X 10.5) always return 0 as keycode for non-english chars. Safari returns the right code, in any language.

    This is important because your user's default language might be set to something else.

  • Liel Dulev

    I should note that you are able to get the right charCode (!) for most languages in FF using the keypress event. But due to the major difference in behavior between browsers regarding event raising of key pressed using this method is a bit tricky/hackable.

  • Liel Dulev

    I should note that you are able to get the right charCode (!) for most languages in FF using the keypress event. But due to the major difference in behavior between browsers regarding event raising of key pressed using this method is a bit tricky/hackable.

  • Mahaq77

    How to prevent the user from using “ENTER” key in quick succession on a text field. On first time using “ENTER” key my form saves, but on using it in quick succession (more than one hit) it crashes.

    Can anybody provide me a quick solution…