Tutorialspoint.dev

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.

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

/div>

Output:
After pressing run button-
keydown output initial

After pressing any key-
output keydown method



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter