views:

95

answers:

4

Hello,

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

Thanks

+3  A: 

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

marcgg
`window.captureEvents` is obsolete and has been removed from newer versions of Firefox, and never supported by some other browsers. See https://developer.mozilla.org/en/DOM/window.captureEvents.
Andy E
This won't work in IE, in which `e` will not be defined.
Tim Down
@andy, @tim: true, I copied and pasted blindly. I corrected my answer. Of course now @tim's answer was the fastest and more accurate
marcgg
A: 

Hi,

jQuery has a nice KeyPress function which allows you to detect a key press, then it should be just a case of detecting the keyvalue and performing an if for the ones you want to ignore.

edit: for example:

$('#target').keypress(function(event) {
  if (event.keyCode == '13') {
     return false; // or event.preventDefault();
  }
});
Luke Duddridge
he's apaprently not using jquery based on the tags he set
marcgg
i don't have a problem with using jquery beside that i'm using ASP.NET
Jack
How can I do it. ?!
Jack
@Luke: Does jQuery normalize the `keypress` event? It behaves differently across browsers, so I would be interested to know if jQuery solves those differences.
Andy E
@Andy E's Head: I am a great believer in all things jQuery, but I am no expert. From what I have read, I'm pretty sure jQuery is cross browser, and according to their site supports IE6+ FF2+ Chrome and Safari. If there are different behaviours for the keypress event, I am sure they have covered it.
Luke Duddridge
@Luke: I envy your optimism.
Beska
A: 

Just return false. Beware that on Opera this doesn't work. You might want to use onkeyup instead and check the last entered character and deal with it. Or better of use JQuery KeyPress

redben
+2  A: 

If you're only interested in the example keys you mentioned, the keydown event will do, except for Opera, 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;
    }
};
Tim Down
+1, I deleted my answer in favour of this one, I wasn't aware of the Opera issues :-)
Andy E