Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus on field after keydown event without inserting character

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">
like image 937
Paran0a Avatar asked Jan 12 '16 10:01

Paran0a


People also ask

Should I use Keyup or Keydown?

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.

What is the difference between Keyup and Keydown?

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.

What is the difference between keypress and Keydown and Keyup?

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.

How do you trigger a key press?

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').


2 Answers

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">
like image 54
Rory McCrossan Avatar answered Oct 01 '22 11:10

Rory McCrossan


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">
like image 34
arshad Avatar answered Oct 01 '22 11:10

arshad