jQuery keydown

When you press a key on the keyboard, the keydown() event is occurred and once the keydown() event is occurred, it executes the function associated with keydown() method to run.

The keydown() event is generally used with two other events.

  • Keypress() event: It specifies that the key is pressed down.
  • Keyup() event: It specifies that the key is released.

Syntax:

$(selector).keydown()  

It triggers the keydown event for selected elements.

$(selector).keydown(function)  

It adds a function to the keydown event.

Parameters of jQuery keydown() event

ParameterDescription
FunctionIt is an optional parameter. It is executed itself when the keydown event is triggered.

Example of jQuery keydown() event

Let’s take an example to demonstrate jQuery keydown() event.


  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="https://code.jquery.com/jquery-1.10.2.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     $("input").keydown(function(){  
  8.         $("input").css("background-color", "green");  
  9.     });  
  10.     $("input").keyup(function(){  
  11.         $("input").css("background-color", "violet");  
  12.     });  
  13. });  
  14. </script>  
  15. </head>  
  16. <body>  
  17. Write something: <input type="text">  
  18. </body>  
  19. </html>   

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *