Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

jQuery | Keydown() with Examples

  • Last Updated : 13 Feb, 2019

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.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!




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

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.




<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>
  
 
 
             

Output:
After pressing run button-
keydown output initial

After pressing any key-
output keydown method




My Personal Notes arrow_drop_up
Recommended Articles
Page :