Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Capturing Enter key WITHOUT JS Framework

Tags:

javascript

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!

like image 536
JamesBrownIsDead Avatar asked Dec 18 '25 23:12

JamesBrownIsDead


1 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

like image 73
halfdan Avatar answered Dec 20 '25 14:12

halfdan