Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I capture a CTRL-S without jQuery or any other library?

Tags:

javascript

dom

How do I go about capturing the CTRL + S event in a webpage?

I do not wish to use jQuery or any other special library.

Thanks for your help in advance.

like image 828
Jason Kelly Avatar asked Jul 06 '12 12:07

Jason Kelly


3 Answers

An up to date answer in 2020.

Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:

document.addEventListener('keydown', e => {
  if (e.ctrlKey && e.key === 's') {
    // Prevent the Save dialog to open
    e.preventDefault();
    // Place your code here
    console.log('CTRL + S');
  }
});

Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.

like image 122
Teemu Avatar answered Oct 30 '22 16:10

Teemu


If you're just using native / vanilla JavaScript, this should achieve the results you are after:

var isCtrl = false;
document.onkeyup=function(e){
    if(e.keyCode == 17) isCtrl=false;
}

document.onkeydown=function(e){
    if(e.keyCode == 17) isCtrl=true;
    if(e.keyCode == 83 && isCtrl == true) {
        //run code for CTRL+S -- ie, save!
        return false;
    }
}

What's happening?

The onkeydown method checks to see if it is the CTRL key being pressed (key code 17). If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.

We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.

like image 29
Matt Gifford Avatar answered Oct 30 '22 16:10

Matt Gifford


document.onkeydown = function(e) {
    if (e.ctrlKey && e.keyCode === 83) {
        alert('hello there');

        // your code here
        return false;
    }
};

You need to replace document with your actual input field.

DEMO

like image 10
Blaster Avatar answered Oct 30 '22 16:10

Blaster