Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling 'ctrl+s' keypress event for browser

I was trying to implement the CTRL+S feature for a browser based application. I made a search and came across two scripts in the following to questions

Best cross-browser method to capture CTRL+S with JQuery?
Ctrl+S preventDefault in Chrome

However, when I tried to implement it, it worked but, I still get the default browser save dialog box/window.

My Code:For shortcut.js:

 shortcut.add("Ctrl+S",function() {
     alert("Hi there!");
 },
 {
     'type':'keydown',
     'propagate':false,
     'target':document
});

jQuery hotkeys.js:

$(document).bind('keydown', 'ctrl+s', function(e) {
    e.preventDefault();
    alert('Ctrl+S');
    return false;
});

I believe e.preventDefault(); should do the trick, but for some reason it doesn't work. Where am I going wrong.Sorry if it is simple, still learning jJvascript.

like image 370
coderunner Avatar asked Jan 28 '13 12:01

coderunner


People also ask

How do I disable Ctrl S in my browser?

To prevent the default behavior when Ctrl+S is Pressed in Chrome, we can use the jQuery bind method to listen to the keydown event. Then in the keydown event handler, we can check if Ctrl+S is pressed. And if it's pressed, we return false and call preventDefault .

How do you keypress an event?

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .

What is keypress function?

The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).

Which event is triggered only once when the keyboards key is pressed?

The keydown event is fired when a key is pressed. Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.


2 Answers

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);
like image 62
coderunner Avatar answered Oct 06 '22 22:10

coderunner


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

like image 38
carkod Avatar answered Oct 06 '22 23:10

carkod