jQuery keydown and keyup Events


keydown


The keydown event is is fired when you press a key. In Firefox and Opera, the keydown event only fires once. In Internet Explorer and Safari, the keydown event behaves just like the keypress event - it fires over and over as long as the key is pressed.

keyup


The keyup event is triggered when you release a key.

Let us learn with a simple example.


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
</script>
<script>
numberofchars=0;
$(document).ready(function(){
  $("input").keydown(function(){
    $("input").css("background-color","lightblue");
  });
  $("input").keyup(function(){
    $("input").css("background-color","yellow");
     $("span").text(numberofchars+=1); 
  });
});
</script>
</head>
<body>

Enter text <input type="text">
<p>Enter any text in the field. The background color will change as the keydown and keyup events trigger.</p>
<p>Number of Characters entered <span>0</span> </p>
</body>
</html>




You may like to try this example here.