Skip to content
Related Articles
Open in App
Not now

Related Articles

jQuery Keydown() Method

Improve Article
Save Article
Like Article
  • Last Updated : 18 Nov, 2022
Improve Article
Save Article
Like Article

The jQuery keydown() is an inbuilt method 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. 

Example 1: Below code is used to check if a key is on its way down. 

HTML




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

Output: 

 

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

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Jquery | Keydown() </title>
    <script src=
    </script>
  
    <script>
        $(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');
        });
    </script>
</head>
  
<body>
    <h1>Try pressing any key from the keyboard </h1>
</body>
  
</html>

Output: 

 


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!