Reputation: 1194
I am trying to override the browser save shortcut i.e. Ctrl+S to give the functionality of save in my web App , I am using Google Chrome... I tried keydown listener to observe the keycode but when two keys i.e. Ctrl+S are pressed simultaneously, keycode of S is never returned in event object.
Upvotes: 36
Views: 13820
Reputation: 145
Actually e.keyCode and navigator.platform both are deprecated instead you can use below code.
document.addEventListener(
"keydown",
function (e) {
if ((e.metaKey || e.ctrlKey) && e.code === "KeyS") {
console.log("CTRL + S pressed");
e.preventDefault(); // Prevent default browser behavior
}
},
false
);
Upvotes: 2
Reputation: 177550
You receive two keydown events: The first is for the control key, and the second is for the letter with the modifier flag turned on. Here's how you listen for a key with a modifier pressed:
document.addEventListener("keydown", function(e) {
if (e.keyCode === 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
e.preventDefault();
// Process event...
}
}, false);
keyCode === 83
corresponds to S key press.
Taking a page from Google Docs, it uses Cmd-S on Mac and Ctrl-S on other platforms.
Upvotes: 54