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
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
4 Comments
Russ Cam
I think you meant event.keycode
=== 13 (or == at the very least)Tim Down
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
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.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;
}
};