Menu

How to Ctrl + S to save in JavaScript

How to Ctrl + S to save in JavaScript

The Ctrl + s shortcut has become so natural as a saving mechanism, that I find myself doing it automatically many times with websites. If you are building an editor of some kind, like a text editor, it might makes sense to begin to include it as a feature. So the following is a quick script to do just that. I use it myself on the custom CMS that runs this blog.

"Control + s" essentially comes down to 2 things. The first being capturing the control key and flagging it so that we know that it is pressed and being held down.

And secondly, capturing the 's' key press right after. If both of these things are true, then you have yourself a ctrl+s mechanism.

Note: Now you don't necessarily want to do this all of the time, because you do end up hijacking the browser's own ctrl+s functionality, typically saving the page, but if you're application calls for it then here is a quick implementation of that functionality.

First up, let's get the keycode for the Ctrl key. Using the keycode lookup chart I have here, we can see that ctrl translates to a 17 keycode.

So let's assume that you have the following markup on your page. Just a standard text field and a label to show us when something is saved.

<form>
    <textarea id='txtInput'></textarea>

<div id='status'></div> </form>

We can attach the following event listener to the input field to capture which key has been pressed.

var isCtrl = false;
window.addEventListener('load', function(){
    document.getElementById('txtInput').addEventListener('keydown', function(e){
        if (e.keyCode == 17) {
            e.preventDefault();
            isCtrl = true;
        }
    });
});

Whenever the keycode of 17 is detected, we set the isCtrl flag to true to imply that we are still holding down on the key.

Next up, we'll also need to listen (in the same event handler as above) for the 's' key press. Which translates to an 83 keycode.

var isCtrl = false;
window.addEventListener('load', function(){
    document.getElementById('txtInput').addEventListener('keydown', function(e){
        if (e.keyCode == 17) {
            e.preventDefault();
            isCtrl = true;
        }


	if (e.keyCode == 83 && isCtrl){
           e.preventDefault();
           // your save logic goes here
	   document.getElementById('status').innerHTML = 'saved';
	}
    });
});

You will need to preventDefault on the 's' key event in order to stop the browser from attempting its own 'save' mechanism. Otherwise, you will still see the save dialog appear that the browser provides.

But if both keys are being pressed, then you can run your own custom code in this section. For this example, we're just simply updating the status.

And lastly, we need to clear the Ctrl flag by setting it back to false once we are done. We can do that with the following event handler.

document.getElementById('txtInput').addEventListener('keyup', function(e){
            e.preventDefault();
            isCtrl = false;
    });

You can technically use the "Ctrl + Key" combination above for any custom functionality that you may have. The Save mechanism is just one potential use-case.

But also, be mindful of overriding any browser behavior in the process as well. Users expect their browsers to behave in certain ways and to perform certain actions, such as typing "Ctrl + p" to print. Overriding that behavior could lead to a poor user experience.

You can find a live version of this code over on my CodePen here.

View code on CodePen

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

V
V@no
6/10/2023 4:39:00 PM
Why not simply check for e.ctrlKey flag? No need for extra isCtrl variable or keyup event listener
Ad Unit

Current Poll

Total Votes:
Q:
Submit

Add a comment