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
2009-12-02 23:35:41
I think you meant event.keycode `===` 13 (or `==` at the very least)
Russ Cam
2009-12-02 23:42:23
Indeed, sorry for that. I fixed that in the code.
halfdan
2009-12-02 23:50:46
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
2009-12-02 23:53:41
... and fourth, `document.body.onkeypress` doesn't work in Firefox or IE: it needs to be `document.onkeypress`.
Tim Down
2009-12-02 23:56:48
Fixed. But this worked for me for quite some time now.
halfdan
2009-12-03 00:21:40
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
2009-12-03 12:47:38
+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
2009-12-02 23:48:45