jQuery keydown() Method

Last Updated:

jQuery keydown() Method

The jQuery keydown() method is used for the following 2 purpose

  1. To run a callback when a keyboard key is down in a specified element.
  2. To trigger the keydown event of a specified element.

Run a Callback

In the following example, we will run a callback functionwhen a keyboard key is down in any input.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery keydown() Method</h1> <input type="text" placeholder="type something"> <script> $(document).ready(function(){ $("input").keydown(function(){ alert("Key is down"); }); }); </script> </body> </html>

Syntax

$(selector).keydown(callback);

Parameter Values

ValueTypeExplanation
callback Optional Specifies a function to be called once the key is down.

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
keydown()YesYesYesYesYesYesYesYesYesYesYesYesYes

Trigger a keydown Event

In the following example, we will trigger a keydown event when a button is clicked.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery keydown() Method</h1> <input type="text" placeholder="type something"> <button>Trigger keydown Event</button> <script> $(document).ready(function(){ $("input").keydown(function(){ alert("Key is down"); }); $("button").click(function(){ $("input").keydown(); }); }); </script> </body> </html>

keydown() vs keypress() vs keyup()

Check out the difference between keydown() vs keypress() vs keyup() in jquery.

Share this Page

Meet the Author