Wednesday, December 8, 2021

ctrl-s or cmd-s listeners to save in vanilla js

 I'm rewriting my blog's homebrew content management pages.

One idiosyncratic feature I like for my own use: my brain sometimes assumes "cmd-s" (ctrl-s in windows speak) should save the current entry, just like I saving a file in a local editor, the fact that I'm working in a browser be damned.

Here is the code I came up with. (I wrote similar stuff a long while back, but it was tied into JQuery, and now I'm all about the Vanilla baby!)

First, adding a listener when the page is loaded:

document.addEventListener('DOMContentLoaded', setupCmdSListeners, false);

Now on my page I have different fields that submit to different forms, so I'll just have it so the main textarea for each content type fakes a click on the submit button for that page:

function setupCmdSListeners(){
    setupCmdSListener('rawguts','submitraw');
    setupCmdSListener('quickguts','submitquick');    
}

We have to curry a function so that each listener knows which submit button is relevant

function setupCmdSListener(textareaid, submitid){
    document.getElementById(textareaid).addEventListener('keydown', 
                (event) => {cmdSListener(event,submitid) });   
}

And here's the actual listener:

function cmdSListener(event,submitid){
    if((event.ctrlKey || event.metaKey) && event.which == 83) {
        document.getElementById(submitid).click();
        event.preventDefault();
        return false;
    }
}

Pretty simple! A page could also just set up the listener for the whole page, and avoid the currying. Sometimes it's easier to write some code than train my brain and hands not to expect something like ctrl-S/cmd-S to work.



No comments:

Post a Comment