Overwrite CMD+S / CTRL+S in Javascript

Posted on 15. September 2014

Do you often work with backend forms in your web application scrolling endless down to the submit button? Why not overwrite the submit button with the common use save keyboard hotkeys CMD+S (Mac) and CTRL+S (Win) with Javascript?

At first, we need to catch the event when a key is pressed:

document.addEventListener("keydown", function(e) { }, false);

Second, we need to get the key code for the S key – it is 83. Mac’s CMD key is represented by metaKey and Windows’s CTRL key is represented by ctrlKey.

You can check which operating system is used by evaluating the property of window.navigator.platform.

Don’t forget to prevent the default executing of the shortcut by calling preventDefault() on the submitted event!

Complete Javascript code

document.addEventListener("keydown", function(e) { if ((window.navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey) && e.keyCode == 83) { e.preventDefault(); // Process the event here (such as click on submit button) } }, false);
Made with ♥️ and Gatsby © 2024