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!

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

4 Comments

I think you meant event.keycode === 13 (or == at the very least)
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.
... and fourth, document.body.onkeypress doesn't work in Firefox or IE: it needs to be document.onkeypress.
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.
2

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;
    }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.