jQuery keydown event

Filed Under: jQuery

jQuery keydown is one of the keyboard event methods. Other jQuery keyboard event methods are keyup and keypress.

jQuery keydown

jQuery keydown method triggers when you first press a key on the keyboard and hold it. You can attach functions to execute when this event occurs.

jQuery keydown method syntax

  1. keydown(): This jQuery keydown method is used without any arguments.
  2. keydown(handler): This jQuery keydown method attaches a function to be executed when the keydown event is fired.

jQuery keydown example

Following example demonstrates the use of jQuery keydown method.

jquery-keydown.html


<!DOCTYPE html>
<html>
<head>
<title>jQuery keydown event example</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function(){
  $("input:text").keyup(function(){
    $("input:text").css("background-color","red");
  });
$("input:text").keydown(function(){
    $("input:text").css("background-color","green");
  });
$("input:text").keypress(function(){
    $("input:text").css("background-color","yellow");
  });
  //reset jQuery keydown css
  $("input:reset").click(function(){
    $("input:text").css("background-color","white");
  });
});
</script>
</head>
<body>
<h3>jQuery keydown example</h3>
Enter anything: <input type="text">
<input type="reset">
<br><br>
Type something above and hold the key, background colour will change to Green.
<br><br>
Click on Reset button to try again.
</body>
</html>

In above example, when the key is pressed and hold, keydown() method is triggered which in turn executes the function that changes the background colour to green.

Below screencast shows above jQuery keydown example in action.

jquery keydown event

jQuery keydown demo

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages