jQuery - .keydown()?

.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:

    • Real-time validation

    • Detecting shortcuts

    • Games or interactive apps

  • e.key → the actual key pressed

  • e.keyCode → numeric code of the key (older browsers)


27️⃣ .keyup()

What it does

  • Fires when a key is released.

  • Also detects all keys, including special keys.

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

  • Fires after the key is released

  • Useful for:

    • Counting characters after typing

    • Live search input

    • Triggering actions after key input is done