.keydown()
What it does
-
Fires as soon as a key is pressed down.
-
Detects all keys, including special keys like Shift, Ctrl, Arrow keys, etc.
Syntax
$(selector).keydown(function(event){
// code here
});
Example
<input type="text" id="name">
<script>
$("#name").keydown(function(e){
console.log("Key pressed: " + e.key); // e.key gives the key value
});
</script>
Key Points
-
Fires repeatedly if key is held down (auto-repeat)
-
Can be used for:
-
e.key → the actual key pressed
-
e.keyCode → numeric code of the key (older browsers)
27️⃣ .keyup()
What it does
Syntax
$(selector).keyup(function(event){
// code here
});
Example
<input type="text" id="name">
<script>
$("#name").keyup(function(e){
console.log("Key released: " + e.key);
});
</script>
Key Points