Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel the keydown in HTML

How can I cancel the keydown of a specific key on the keyboard, for example(space, enter and arrows) in an HTML page.

like image 409
Jack Avatar asked Jun 14 '10 09:06

Jack


People also ask

How do I stop key press?

How do I turn off keypress events? Alternatively, you could attach another event handler to the input field, and in this handler stop the propagation of the event: jQuery('#input-field-id'). bind('keypress', function(e) { e. stopPropagation(); });

How do you prevent a number from Keydown?

Use the keypress event instead. It's the only key event which will give you information about the character that was typed, via the which property in most browsers and (confusingly) the keyCode property in IE. Using that, you can conditionally suppress the keypress event based on the character typed.

What does the Keydown () do?

The keydown event is sent to an element when the user presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. It can be attached to any element, but the event is only sent to the element that has the focus.

What is the difference between keypress () and Keydown ()?

keydown – fires when any key is pressed down, fires first, and always before the browser processes the key (e.g. inserting text, moving focus, etc). keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key.


2 Answers

If you're only interested in the example keys you mentioned, the keydown event will do, except for older, pre-Blink versions of Opera (up to and including version 12, at least) where you'll need to cancel the keypress event. It's much easier to reliably identify non-printable keys in the keydown event than the keypress event, so the following uses a variable to set in the keydown handler to tell the keypress handler whether or not to suppress the default behaviour.

var cancelKeypress = false;

document.onkeydown = function(evt) {
    evt = evt || window.event;
    cancelKeypress = /^(13|32|37|38|39|40)$/.test("" + evt.keyCode);
    if (cancelKeypress) {
        return false;
    }
};

/* For Opera */
document.onkeypress = function(evt) {
    if (cancelKeypress) {
        return false;
    }
};
like image 85
Tim Down Avatar answered Sep 19 '22 15:09

Tim Down


Catch the keydown event and return false. It should be in the lines of:

<script>
document.onkeydown = function(e){
  var n = (window.Event) ? e.which : e.keyCode;
  if(n==38 || n==40) return false;
}
</script>

(seen here)

The keycodes are defined here

edit: update my answer to work in IE

like image 22
marcgg Avatar answered Sep 19 '22 15:09

marcgg