I have a shortcut key K. It should focus on my input, but I don't want it to insert the letter K
when it focuses.
$(document).keydown(function(event) {
if (event.which == 75) {
$('input').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text">
Both are used as per the need of your program and as per the convenience of the user. keyup Fires when the user releases a key, after the default action of that key has been performed. keydown Fires when the user depresses a key.
The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.
keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key. keyup – fires when any key is released, fires last, and the browser processes the key.
If you want to trigger the key-events with specific keys, you can do so like this: $(function() { var e = $. Event('keypress'); e. which = 65; // Character 'A' $('item').
You can use event.preventDefault()
to stop the standard behaviour of the event. Note however that this will stop the letter K
from being able to be typed in the input
. To allow that you need to add a keydown
handler to the input
itself which stops the event propagation reaching the document
. Try this:
$(document).keydown(function(event) {
if (event.which == 75) {
event.preventDefault();
$('input').focus();
}
});
$('input').keydown(function(e) {
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text">
This is another way:
At the time of keydown, if it is k
and the input does not have focus then prevent the default behavior and give focus to the text field.
$(document).keydown(function(event) {
if (event.which == 75 && !$('input').is(":focus")) {
event.preventDefault();
$('input').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With