jQuery keydown() Method triggers the keydown event when any button on the keyboard is pressed down. Unlike keypress() Method which doesn’t consider keys such as ALT, CTRL, SHIFT, ESC, the keydown() method considers these keys as well while triggering keydown event. This method attaches an html element to event handler function, this event handler function executes when the keydown event occurs.
keypress() vs keydown()
The keypress() Method doesn’t trigger keypress event when any of the special keys such as ALT, CTRL, SHIFT, ESC are pressed, if you want to check for these keys then use keydown() method instead.
jQuery keydown() Method Syntax
$("input").keydown(function(){ //this code executes when a key is pressed down. });
Here we have attached the event handler function to input text field ($(“input”)) using keydown() method, this way the keydown event will only trigger when the key is pressed inside the text field. If you like, you can select any other html element using jQuery selector.
jQuery keydown() Example
In the following example we have attached the input text field to event handler function using keydown() method. This makes the keydown event to trigger when a key is pressed down inside the input field.
Here we are changing the background colour of the input field inside the event handler function, which means when the keydown event triggers, the background colour of input field changes.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("input").keydown(function(){ $("input").css("background-color", "green"); }); }); </script> </head> <body> <h2>jQuery keydown event example on Beginnersbook.com</h2> Write anything here: <input type = "text"> <p>The background color of input text field will change to green, when you press a key inside the input field.</p> </body> </html>
Output:
Before a key is pressed down:
This screenshot is taken before we have performed any activity on the page.
After a key is pressed down inside the input text field:
This screenshot is taken after we have pressed down a key inside input field. As you can see in the screenshot that the background colour of the input field changes to green.
Leave a Reply