Reputation: 43
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!
Upvotes: 2
Views: 264
Reputation: 34254
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
Upvotes: 7
Reputation: 324727
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;
}
};
Upvotes: 2