tags:

views:

85

answers:

2

How can I detect when the "Enter" key is pressed in the window, and conditionally suppress it? I've found lots of solutions with jQuery and MooTools, but not a frameworkless version. Thanks!

+5  A: 

Hi, you do that by adding a function to the onkeypress event of your documents body.

document.onkeypress = function (event) {
    event = event || window.event;
    if (event.keyCode === 13) {
       alert('Enter key pressed');
       return false;
    }
    return true;
}

To suppress any further action you'll have to return false at the end of the function.

Best wishes, Fabian

halfdan
I think you meant event.keycode `===` 13 (or `==` at the very least)
Russ Cam
Indeed, sorry for that. I fixed that in the code.
halfdan
Have you tested this? I don't think it will work in any browser. First, `keyCode` will be 0 for printable character keypresses in Firefox, for example. Second, as Russ Cam pointed out, you're missing an equals sign. Third, you have mis-typed "keyCode": note the capital "C" in the middle.
Tim Down
... and fourth, `document.body.onkeypress` doesn't work in Firefox or IE: it needs to be `document.onkeypress`.
Tim Down
Fixed. But this worked for me for quite some time now.
halfdan
In the specific case of the enter key I will grant you that you do get 13 for `keyCode` in Firefox, so my first point was invalid, though the general principle remains true.
Tim Down
+1  A: 

This will work in all current mainstream browsers:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.keyCode || evt.which;
    if (charCode == 13) {
        alert("Enter");
        if (evt.preventDefault) {
            evt.preventDefault();
        } else {
            evt.returnValue = false;
        }
        return false;
    }
};
Tim Down