Monday, October 2, 2006

How to detect Enter key event

At the end of the page add this javascript:


function enterPressed(evn) {
if (window.event && window.event.keyCode == 13) {
alert("IE: Enter is pressed");
} else if (evn && evn.keyCode == 13) {
alert("Netscape: Enter is pressed");
}
}
document.onkeypress = enterPressed;

UPDATE

Here is modified cross browser version of the code above:

function doWhenEnterPressed(evn) {
var enterWasPressed = false;
if (window.event && window.event.keyCode == 13) { // IE
enterWasPressed = true;
} else if (evn && (evn.keyCode == 13 || evn.which == 13 )) { // FF
enterWasPressed = true;
}
if (enterWasPressed) {
alert('Enter pressed'); // your action code
}
}

document.onkeydown = function(evn) {
doWhenEnterPressed(evn);
}