Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The onkeypress
property of the GlobalEventHandlers
mixin is an event handler that processes keypress
events.
The keypress
event should fire when the user presses a key on the keyboard. However, in practice browsers do not fire keypress
events for certain keys.
Warning: The onkeypress
event handler has been deprecated. You may want to use onkeydown
instead.
target.onkeypress = functionRef;
functionRef
is a function name or a function expression. The function receives a KeyboardEvent
object as its sole argument.
This example logs the KeyboardEvent.code
value whenever you press a key inside the <input>
element.
HTML
JavaScript
const input = document.querySelector('input');
const log = document.getElementById('log');
input.onkeypress = logKey;
function logKey(e) {
log.textContent += `${e.code}`;
}
Result
This example filters the characters typed into a form field using a regular expression.
HTML
<label>Enter numbers only:
<input>
</label>
JavaScript
function numbersOnly(event) {
return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));
}
const input = document.querySelector('input');
input.onkeypress = numbersOnly;
input.onpaste = event => false;
Result
The following JavaScript function will do something after the user types the word "exit" in any point of a page.
(function () {
const sSecret = "exit";
let nOffset = 0;
document.onkeypress = function(oPEvt) {
let oEvent = oPEvt || window.event,
nChr = oEvent.charCode,
sNodeType = oEvent.target.nodeName.toUpperCase();
if (nChr === 0 ||
oEvent.target.contentEditable.toUpperCase() === "TRUE" ||
sNodeType === "TEXTAREA" ||
sNodeType === "INPUT" && oEvent.target.type.toUpperCase() === "TEXT") {
return true;
}
if (nChr !== sSecret.charCodeAt(nOffset)) {
nOffset = nChr === sSecret.charCodeAt(0) ? 1 : 0;
} else if (nOffset < sSecret.length - 1) {
nOffset++;
} else {
nOffset = 0;
alert("Yes!!!");
location.assign("https://developer.mozilla.org/");
}
return true;
};
})();
Note: A more complete framework for capturing the typing of hidden words is available on GitHub.