js add event to keypress code example

Example 1: how do i listen to a keypress in javascript

let b = document.getElementById("body"); //making var for body
b.addEventListener("keydown", (evt) => {//when this happens
	console.log(evt.keyCode); //log keycode
});

Example 2: 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