jQuery Tutorial Tutorials - jQuery .keydown(handler) method

jQuery .keydown() method

The .keydown() method in jQuery is used to bind an event handler to the keydown event on the elements.

The .keydown() method is also used to trigger the keydown event on an element.

jQuery .keydown() method Syntax

.keydown()
.keydown(handler)
.keydown(eventData,handler)
Parameter Type Description
handler Function A function to execute when the keydown is triggered on the matched element.
eventData Anything Additional data passed to the event handler.

jQuery .keydown() method Example

example

Use .keydown() without an argument to trigger a keydown event on element.
HTML

<form>
    <input id="target" type="text" value="Hello there">
</form>
<div id="other">
    Trigger the handler
</div>
$( "#target" ).keydown(function() {
    console.log( "Handler for .keydown() called." );
});

$( "#other" ).click(function() {
    $( "#target" ).keydown(); // trigger the event
});

jQuery .keydown(handler) method Example

Note that when using keydown() method,the keyCode of A and a are the same. A=65 , a=65.

example

To trigger the keydown event specified by key code,you should use trigger() method.

var event = $.Event("keydown");
// e.keyCode= 13; // the enter key code
event.which = 49; // Character '1'
event.keyCode = 49;
event.key = 1;
$("input[name=username]").trigger(event);

Try now

jQuery .keydown() VS .keypress()

There are two differences between keydown() and keypress() in jQuery.

In older verion,keydown keeps firing if the key is kept pressed, while keypress and keyup fire only once.

example

when using keydown(),it's case insensitive,the keyCode of A and a are the same. A=65 , a=65.
keypress() is case sensitive,the keyCode of A and a are: A=65 , a=97.

The difference between keydown() and keypress() when capturing the keyCode and which
Try now

example

When user press the special key such as Shift, Esc, and delete,only the keydown event is fired.

The difference between keydown() and keypress() when processing special key.
Try now

Date:2019-08-29 19:35:12 From:www.Lautturi.com author:Lautturi