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:

snippet
$(selector).keydown()

It triggers the keydown event for selected elements.

snippet
$(selector).keydown(function)

It adds a function to the keydown event.

Parameters of jQuery keydown() event

Parameter Description
Function It 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.

snippet
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
    $("input").keydown(function(){
        $("input").css("background-color", "green");
    });
    $("input").keyup(function(){
        $("input").css("background-color", "violet");
    });
});
</script>
</head>
<body>
Write something: <input type="text">
</body>
</html>

Output:

Note
Note: If you write something in the above text box then the background color will be changed on keydown and keyup.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +