Handling 'ctrl+s' keypress event for browser

允我心安 提交于 2019-11-29 02:09:50

You don't need any of those libraries, just try this:

$(document).on('keydown', function(e){
    if(e.ctrlKey && e.which === 83){ // Check for the Ctrl key being pressed, and if the key = [S] (83)
        console.log('Ctrl+S!');
        e.preventDefault();
        return false;
    }
});

The problem was that your code halted at the alert(), preventing your function from interrupting the save dialogue.

(Still uses jQuery)

This is to just add a different implementation to the question used by me. Adapted from a SO answer.Also,works for MAC

 document.addEventListener("keydown", function(e) {
      if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey))      {
        e.preventDefault();
        //your implementation or function calls
      }
    }, false);

People are still viewing this it seems, so it's probably worth pointing out that there is no need for jQuery on this one, here:

function keydown (event) {
    var isCtrlKeyDown = navigator.platform.indexOf("Mac") > -1 ? event.metaKey : event.ctrlKey,
        isSDown = (event.key && event.key === "s") || (event.keyCode || event.which) === 83 // falls back to keycode if no event.key

    if (isCtrlKeyDown && isSDown) {
        // prevent default event on newer browsers
        if (event.preventDefault) {
            event.preventDefault()
        }


        // ... your code here ...


        // prevent default event on older browsers
        return false
    }
}

// register the event
if (document.addEventListener) {
    document.addEventListener("keydown", keydown)
} else {
    document.onkeydown = keydown
}

That should work in all browsers, this will also work for folks using alternative keyboard layouts from QWERTY on Windows, which reports incorrect key codes (at least on Chrome 56 on Windows 10 in my testing)

However, this looks kind of clunky, and confusing, so if you are only supporting modern browsers, you can do the following instead:

document.addEventListener("keydown", function keydown (event) {
    if (navigator.platform === "MacIntel" ? event.metaKey : event.ctrlKey && event.key === "s") {
        event.preventDefault()

        // ... your code here ...
    }
})

No need to use any plugin, just use below jquery code

$(document).bind('keydown', 'ctrl+s', function (e) {
        if (e.ctrlKey && (e.which == 83)) {

            e.preventDefault();
            //Your method()
            return false;
        }
    });

Since you are using alert, the execution halts at the alert and "return false" is not executed until you close the alertbox, thats the reason you see the default dialog.

If your method is long running better use asyn method method instead.

As of 2017, instead of using e.keyCode === 83 you should use e.key === 's' as the former is deprecated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!