jQuery | Keydown() with Examples

The keydown() is an inbuilt method in jQuery which is used to trigger the keydown event whenever User presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. So, Using keydown() method we can detect if any key is on its way down.
Syntax:

$(selector).keydown(function) 

Here selector is the selected element.
Parameter: It accepts an optional parameter as a function which gives the idea whether any key is pressed or not.
Return values: It returns whether any key is pressed or not or which key is pressed.
jQuery code to show the working of keydown() Method:
Code #1:
Below code is used to check if a key is on its way down.

filter_none

edit
close

play_arrow

link
brightness_4
code

<title>Jquery | Keydown() </title>
    $(document).keydown(function(event) {
  
        alert('You pressed down a key');
    });
  
  
      
        <h1>Try pressing any key from the keyboard </h1>
     

chevron_right


Output:
After pressing run button-
keydown output initial

After pressing any key-
Output keydown

Code #2:
Below code is used to check which specific key is pressed down from the keyboard and the event.keyCode and event.which will return a UNICODE value of the pressed key, Both are browser specific.

filter_none

edit
close

play_arrow

link
brightness_4
code

<title>Jquery | Keydown() </title>
  
  
 
 
$(document).keydown(function(event) {
 
    var key = (event.keyCode ? event.keyCode : event.which);
 
    if (key >= '65' && key = '96' && key = '48' && key = '112' && key <= '123')
        alert('You pressed FUNCTION key - ' + (key - 111));
 
    else if (key == '144')
        alert('You pressed NUMLOCK key');
 
    else if (key == '145')
        alert('You pressed SCROLL LOCK key');
 
    else
        alert('You pressed SPECIAL CHARACTER key');
 
});
 
 
 
<br>
<br>
  
    <h1>Try pressing any key from the keyboard </h1>
  
 
 
             

chevron_right


Output:
After pressing run button-
keydown output initial

After pressing any key-
output keydown method



My Personal Notes arrow_drop_up

self motivated and passionate programmer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.