Code has been added to clipboard!

Learn About jQuery .keydown(): Method for Assigning Event Handlers

Reading time 2 min
Published Jan 8, 2018
Updated Sep 27, 2019

jQuery keydown event belongs to the category of jQuery keyboard events. It is triggered when a person presses any key, meaning that the action does have to generate value.

A keydown event is transferred to elements when visitors press a key. If people press the key multiple times, the event is sent to the element every time it's pressed. By using .keydown(), you can invoke the keydown event on specified elements. Additionally, you can assign an event handler to the keydown event.

Make sure not to mix the jQuery keydown event with the keypress event. They are similar, but keydown is invoked by the non-printing keys (differently from the keypress).

jQuery keydown: Main Tips

  • jQuery offers various event methods for assigning specific event listeners.
  • The .keydown() jQuery method attaches an event handler which is triggered the moment the key gets pressed, or triggers the keydown jQuery event.

.keydown() Explained

The .keydown() method does two things. It can either attach an event handler for the keydown event, or simply trigger the mentioned event. As we have indicated before, the event is normally triggered when a key on the keyboard gets pressed.

To simply trigger the keydown jQuery event, use this syntax:

$("selector").keydown();

Example
$("input").keydown(() => {
        alert('Hey, you pressed a button, good for you!'); 
    });

Alternatively, you can use this syntax to attach a function to be executed when the event is triggered:

$("selector").keydown(function)

Look at this simple example implementing this event method. The background color of the input field changes every time a button is pressed:

Example
$("input").keydown(() => {
    $("input").css("background-color", "blue");
});
$("input").keyup(() => {
    $("input").css("background-color", "green");
});

As you can see in the example above, the .keyup() is also used. It is transferred to an element when the user finally releases the key which was pressed on the keyboard. You can read more about it in this tutorial.

jQuery keydown: Summary

  • By using the jQuery .keydown() method, you can assign event handlers for the keydown event, or trigger said event.
  • The .keydown() can be invoked by non-printing keyboard buttons.