document.addEventListener("keydown", (event) => {
const keyName = event.key;
if (keyName === "Control") {
// do not alert when only Control key is pressed.
return;
}
if (event.ctrlKey) {
// Even though event.key is not 'Control' (e.g., 'a' is pressed),
// event.ctrlKey may be true if Ctrl key is pressed at the same time.
alert(`Combination of ctrlKey + ${keyName}`);
} else {
alert(`Key pressed ${keyName}`);
}
});
document.addEventListener("keyup", (event) => {
const keyName = event.key;
// As the user releases the Ctrl key, the key is no longer active,
// so event.ctrlKey is false.
if (keyName === "Control") {
alert("Control key was released");
}
});KeyboardEvent / notebook
KeyboardEvent
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.