Open In App

jQuery Keydown() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The jQuery keydown() is an inbuilt method that is used to trigger the key-down event whenever the 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) {
            let 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: 



Last Updated : 07 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads