on key down command javascript code example
Example 1: javascript keydown
document.addEventListener("keydown", function(event) {
if (event.keyCode == 32) {
console.log("Space was pressed!");
}
});
Example 2: js detect cmd+s
document.querySelectorAll('#form').forEach(form => {
let meta_pressed = false;
form.addEventListener('keydown', e => {
if ( e.key === 'Meta' ) {
meta_pressed = true;
} else if ( e.key === 's' ) {
e.preventDefault();
form.submit();
}
});
form.addEventListener('keyup', e => {
if ( e.key === 'Meta' ) {
meta_pressed = false;
}
});
});