key pressed event in javascript code example

Example 1: js when key is pressed

document.addEventListener("keypress", function(event) {
	// do stuff
});

Example 2: html onkeypress

<input type="text" onkeypress="myFunction()">

Example 3: adding event listener keypress event in javascript

let msg = document.getDocumentById('#message');

msg.addEventListener("keydown", (event) => {
    // handle keydown
});

msg.addEventListener("keypress", (event) => {
    // handle keypress
});

msg.addEventListener("keyup", (event) => {
    // handle keyup
});

Tags:

Html Example