0

I'm new to js. How can I check if the client press the key combination ctl+s?

$(document).keypress(function(e) {
  if(e.charCode == 17 && e.charCode == 83) {
    alert("ok");
  }
});

This doesn't work. Jquery is included.

Rohit Sharma
  • 3,304
  • 2
  • 19
  • 34
Markus
  • 407
  • 2
  • 9
  • 25
  • Have you checked your browser console for any errors? Also please note `83` is uppercase **S** and `115` is lowercase **s** – NewToJS Jul 21 '17 at 11:36
  • How would it be possible, that `e.charCode` would be 17 and 83 at the same time? – Teemu Jul 21 '17 at 11:37
  • 1
    Possible duplicate of [Best cross-browser method to capture CTRL+S with JQuery?](https://stackoverflow.com/questions/93695/best-cross-browser-method-to-capture-ctrls-with-jquery) – Carsten Løvbo Andersen Jul 21 '17 at 11:39
  • @NewToJS No erros in the console. Only one of them does not working too. – Markus Jul 21 '17 at 11:39
  • I would just like to add that behaviour expected from "ctrl + s" (on windows and linux) is normally expected from "cmd + s" on macOS, so (depending on what you would like to achieve) you might want to add handling for that too :) – Ola Næss Kaldestad Jul 21 '17 at 11:54

1 Answers1

3

This would work if you are jQuery.

$(document).ready(function() {
  $(document).keydown(function(event) {
    if (event.ctrlKey && event.keyCode == 83) {
      event.preventDefault()
      //action here
      alert('Saved');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Press ctrl +s

Working fiddle here.

If you want to detect cmd + s on mac, you need to use keycodes mentioned below on different-different browsers, beacuse unlike Shift/Alt/Ctrl, Mac/Apple key is not considered as a modifier key--instead, you should hook on keydown/keyup and record when a key is pressed:

Firefox: 224
Opera: 17
WebKit (Safari/Chrome): 91 (Left Apple) or 93 (Right Apple)

I got from here.

And if you want close your browser tab on save window.top.close(); will work that I got from here. Also working for me.

Rohit Sharma
  • 3,304
  • 2
  • 19
  • 34