[ACCEPTED]-Best cross-browser method to capture CTRL+S with JQuery?-jquery

Accepted answer
Score: 271

This works for me (using jquery) to overload 1 Ctrl+S, Ctrl+F and Ctrl+G:

$(window).bind('keydown', function(event) {
    if (event.ctrlKey || event.metaKey) {
        switch (String.fromCharCode(event.which).toLowerCase()) {
        case 's':
            event.preventDefault();
            alert('ctrl-s');
            break;
        case 'f':
            event.preventDefault();
            alert('ctrl-f');
            break;
        case 'g':
            event.preventDefault();
            alert('ctrl-g');
            break;
        }
    }
});
Score: 125
$(window).keypress(function(event) {
    if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
    alert("Ctrl-S pressed");
    event.preventDefault();
    return false;
});

Key codes can differ between browsers, so 2 you may need to check for more than just 1 115.

Score: 34

You could use a shortcut library to handle the browser specific 1 stuff.

shortcut.add("Ctrl+S",function() {
    alert("Hi there!");
});
Score: 30

This jQuery solution works for me in Chrome 1 and Firefox, for both Ctrl+S and Cmd+S.

$(document).keydown(function(e) {

    var key = undefined;
    var possible = [ e.key, e.keyIdentifier, e.keyCode, e.which ];

    while (key === undefined && possible.length > 0)
    {
        key = possible.pop();
    }

    if (key && (key == '115' || key == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))
    {
        e.preventDefault();
        alert("Ctrl-s pressed");
        return false;
    }
    return true;
}); 
Score: 28

This one worked for me on Chrome... for 7 some reason event.which returns a capital S (83) for 6 me, not sure why (regardless of the caps 5 lock state) so I used fromCharCode and toLowerCase just to be on 4 the safe side

$(document).keydown(function(event) {

    //19 for Mac Command+S
    if (!( String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19)) return true;

    alert("Ctrl-s pressed");

    event.preventDefault();
    return false;
});

If anyone knows why I get 83 and 3 not 115, I will be happy to hear, also if anyone 2 tests this on other browsers I'll be happy 1 to hear if it works or not

Score: 7

I combined a few options to support FireFox, IE 2 and Chrome. I've also updated it to better 1 support mac

// simply disables save event for chrome
$(window).keypress(function (event) {
    if (!(event.which == 115 && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) && !(event.which == 19)) return true;
    event.preventDefault();
    return false;
});

// used to process the cmd+s and ctrl+s events
$(document).keydown(function (event) {
     if (event.which == 83 && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {
        event.preventDefault();
        save(event);
        return false;
     }
});
Score: 6

$(document).keydown(function(e) {
    if ((e.key == 's' || e.key == 'S' ) && (e.ctrlKey || e.metaKey))
    {
        e.preventDefault();
        alert("Ctrl-s pressed");
        return false;
    }
    return true;
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try pressing ctrl+s somewhere.

This is an up-to-date version of @AlanBellows's 4 answer, replacing which with key. It also works 3 even with Chrome's capital key glitch (where 2 if you press Ctrl+S it sends capital S instead 1 of s). Works in all modern browsers.

Score: 5

I would like Web applications to not override 10 my default shortcut keys, honestly. Ctrl+S already 9 does something in browsers. Having that 8 change abruptly depending on the site I'm 7 viewing is disruptive and frustrating, not 6 to mention often buggy. I've had sites hijack 5 Ctrl+Tab because it looked the same as Ctrl+I, both 4 ruining my work on the site and preventing 3 me from switching tabs as usual.

If you want 2 shortcut keys, use the accesskey attribute. Please 1 don't break existing browser functionality.

Score: 4

@Eevee: As the browser becomes the home 18 for richer and richer functionality and 17 starts to replace desktop apps, it's just 16 not going to be an option to forgo the use 15 of keyboard shortcuts. Gmail's rich and 14 intuitive set of keyboard commands was instrumental 13 in my willingness to abandon Outlook. The 12 keyboard shortcuts in Todoist, Google Reader, and 11 Google Calendar all make my life much, much 10 easier on a daily basis.

Developers should 9 definitely be careful not to override keystrokes 8 that already have a meaning in the browser. For 7 example, the WMD textbox I'm typing into 6 inexplicably interprets Ctrl+Del as "Blockquote" rather 5 than "delete word forward". I'm curious 4 if there's a standard list somewhere of 3 "browser-safe" shortcuts that site developers 2 can use and that browsers will commit to 1 staying away from in future versions.

Score: 1

I like this little plugin. It needs a bit more cross browser 1 friendliness though.

Score: 1

To Alan Bellows answer: !(e.altKey) added 3 for users who use AltGr when typing (e.g Poland). Without 2 this pressing AltGr+S will give same result as 1 Ctrl+S

$(document).keydown(function(e) {
if ((e.which == '115' || e.which == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))
{
    e.preventDefault();
    alert("Ctrl-s pressed");
    return false;
}
return true; });
Score: 0

example:

shortcut.add("Ctrl+c",function() {
    alert('Ok...');
}
,{
    'type':'keydown',
    'propagate':false,
    'target':document
});

usage

<script type="text/javascript" src="js/shortcut.js"></script>

link for download: http://www.openjs.com/scripts/events/keyboard_shortcuts/#

0

Score: 0

This should work (adapted from https://stackoverflow.com/a/8285722/388902).

var ctrl_down = false;
var ctrl_key = 17;
var s_key = 83;

$(document).keydown(function(e) {
    if (e.keyCode == ctrl_key) ctrl_down = true;
}).keyup(function(e) {
    if (e.keyCode == ctrl_key) ctrl_down = false;
});

$(document).keydown(function(e) {
    if (ctrl_down && (e.keyCode == s_key)) {
        alert('Ctrl-s pressed');
        // Your code
        return false;
    }
}); 

0

Score: 0

I solved my problem on IE, using an alert("With a message") to prevent 1 default Behavior:

window.addEventListener("keydown", function (e) {
    if(e.ctrlKey || e.metaKey){
        e.preventDefault(); //Good browsers
        if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { //hack for ie
            alert("Please, use the print button located on the top bar");
            return;
        }
    }
});
Score: 0

This Plugin Made by me may be helpful.

Plugin

You 6 can use this plugin you have to supply the 5 key Codes and function to be run like this

simulatorControl([17,83], function(){
 console.log('You have pressed Ctrl+Z');
});

In 4 the code i have displayed how to perform 3 for Ctrl+S. You will get Detailed Documentation 2 On the link. Plugin is in JavaScript Code 1 section Of my Pen on Codepen.

Score: 0

This was my solution, which is much easier 3 to read than other suggestions here, can 2 easily include other key combinations, and 1 has been tested on IE, Chrome, and Firefox:

$(window).keydown(function(evt) {
  var key = String.fromCharCode(evt.keyCode).toLowerCase();
  switch(key) {
    case "s":
      if(evt.ctrlKey || evt.metaKey) {
        fnToRun();
        evt.preventDefault(true);
        return false;
      }
      break;
  }
  return true;
});

More Related questions