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.
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
- The price matches the quality
- Suitable for learners ranging from beginner to advanced
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
- A wide range of learning programs
- University-level courses
- Easy to navigate
- Verified certificates
- Free learning track available
- University-level courses
- Suitable for enterprises
- Verified certificates of completion
.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();
$("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:
$("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.