21

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

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Jack
  • 213
  • 1
  • 2
  • 4

6 Answers6

22

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.

Example code using addEventListener and ignoring ancient version of Opera

document.addEventListener("keydown", function(evt) {
    // These days, you might want to use evt.key instead of keyCode
    if (/^(13|32|37|38|39|40)$/.test("" + evt.keyCode)) {
        evt.preventDefault();
    }
}, false);

Original example code from 2010

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 pre-Blink Opera */
document.onkeypress = function(evt) {
    if (cancelKeypress) {
        return false;
    }
};
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 5
    +1, I deleted my answer in favour of this one, I wasn't aware of the Opera issues :-) – Andy E Jun 14 '10 at 10:29
  • Does Opera quirk still stand these days and times? You still need to cancel in keypress? – Robert Koritnik Jul 11 '16 at 09:39
  • 1
    @RobertKoritnik: I just tried it and it doesn't apply to the latest version of Opera. I would guess it doesn't apply to any Blink-based version of Opera. – Tim Down Jul 11 '16 at 10:16
  • Thanks. I just wanted to be sure as I'm writing come code that deals wit keydown cancellation and din't want to install Opera just to check this. – Robert Koritnik Jul 11 '16 at 10:28
  • Note that if you alter the value of a textbox within the keydown event when pressing the up arrow, you'll have to use e.preventDefault() to prevent the cursor from appearing at the beginning of the text instead of the end of the text as intended. A very rare caveat, but is used for things such as web-based terminals when a user navigates through command history using the up & down arrow keys. – Mark Entingh Nov 04 '20 at 19:01
  • Does not work... – Epic Speedy Aug 24 '22 at 12:31
  • @EpicSpeedy Example? My guess would be that you're using `addEventListener("keydown")` rather than `onkeydown`, in which case you'll need to use `evt.preventDefault()` rather than `return false`. – Tim Down Aug 25 '22 at 13:46
5

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
  • 65,020
  • 52
  • 178
  • 231
  • 1
    `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 Jun 14 '10 at 10:00
  • @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 Jun 14 '10 at 13:20
  • preventDefault function works for me – Yasin UYSAL Jan 10 '23 at 12:05
1

This is certainly very old thread. In order to do the magic with IE10 and FireFox 29.0.1 you definitely must do this inside of keypress (not keydown) event listener function:

if (e.preventDefault) e.preventDefault();
Aylen
  • 3,524
  • 26
  • 36
0

I only develop for IE because my works requires it, so there is my code for numeric field, not a beauty but works just fine

    $(document).ready(function () {

    $("input[class='numeric-field']").keydown(function (e) {

        if (e.shiftKey == 1) {
            return false
        }

        var code = e.which;
        var key;

        key = String.fromCharCode(code);

        //Keyboard numbers   
        if (code >= 48 && code <= 57) {
            return key;
        } //Keypad numbers
        else if (code >= 96 && code <= 105) {
            return key
        } //Negative sign
        else if (code == 189 || code == 109) {
            var inputID = this.id;
            var position = document.getElementById(inputID).selectionStart
            if (position == 0) {
                return key
            }
            else {
                e.preventDefault()
            }
        }// Decimal point
        else if (code == 110 || code == 190) {
            var inputID = this.id;
            var position = document.getElementById(inputID).selectionStart

            if (position == 0) {
                e.preventDefault()
            }
            else {
                return key;
            }
        }// 37 (Left Arrow), 39 (Right Arrow), 8 (Backspace) , 46 (Delete), 36 (Home), 35 (End)
        else if (code == 37 || code == 39 || code == 8 || code == 46 || code == 35 || code == 36) {
            return key
        }
        else {
            e.preventDefault()
        }
    });

});
0

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
  • 4,285
  • 35
  • 50
  • he's apaprently not using jquery based on the tags he set – marcgg Jun 14 '10 at 09:49
  • i don't have a problem with using jquery beside that i'm using ASP.NET – Jack Jun 14 '10 at 09:51
  • 1
    @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 Jun 14 '10 at 09:54
  • @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 Jun 14 '10 at 10:23
0

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
  • 5,578
  • 5
  • 47
  • 63