Poles
Poles

Reputation: 3682

is it possible to bind ctrl+s on click event in javascript?

I am trying to write a code to bind the save as option on click event.I don't want to use filesaver.js. I want pure javascript to write this code.

Upvotes: 0

Views: 1063

Answers (2)

Brian North
Brian North

Reputation: 1398

HTML5 standards introduced the File API, which should allow scripts to offer up "files" (Blobs) for users to save. Support is shoddy, though, which is why polyfills like FileSaver.js exist. Filesaver.js is "pure" javascript, too, so I'm not sure why needing a pure javascript solution precludes its use (unless you mean you can't load outside scripts - just minify and inline it (along with licence, etc.)) Right now, if you must code it yourself, any cross-browser solution you come up with is likely to be an effective rewrite of the polyfil.

Once you have an implementation of saveAs(), simply attach it to whatever event trigger you like:

myButton.addEventListener( 'click', function() { window.saveAs( fileBlob, 'filename.txt' ) } );

Clarification: As per the W3C spec on Events, all untrusted events (includes key-press events) act as if event.preventDefault() was called - so there is explicitly no way to simulate an actual ctrl+s keypress - only ways to simulate its effects.

Upvotes: 1

RononDex
RononDex

Reputation: 4183

You could do something like this:

var isCtrlPressed = false;

function onKeyDown(event) {
    if (event.keyCode == 17) { // Control got pressed
        isCtrlPressed = true;
    }
    if (event.keyCode == 83) { // "s" got pressed
        // if control is pressed too execute some code
        if (isCtrlPressed) {
            // Your code here
        }
    }
}

function onKeyUp(event) {
    if (event.keyCode == 17) { // Control got pressed
        isCtrlPressed = false;
    }
}

Then on your body tag add the following events:

<body onkeydown="onKeyDown(event)" onkeyup="onKeyUp(event)">
</body>

You can find a lifedemo here: http://jsbin.com/eBIRAfA/1/edit

Upvotes: 0

Related Questions