Categories
JavaScript Answers

How to Prevent the Default Behavior When Ctrl+S is Pressed in Chrome?

Spread the love

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.

For instance, we can write:

$(document).bind('keydown', (e) => {
  if (e.ctrlKey && (e.which === 83)) {
    e.preventDefault();
    return false;
  }
});

We call bind on $(document) to listen to the keydown event on the whole document.

In the event handler, we check is the Ctrl key is pressed with e.ctrlKey.

And we check if the S key is pressed with e.which. 83 is the key code for the S key.

If both are true, then we call e.preventDefault to stop the default behavior.

And we also return false.

To do the same thing with plain JavaScript, we can use the document.addEventListener method.

To use it, we write:

document.addEventListener("keydown", (e) => {
  if (e.key === 's' && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
    e.preventDefault();
  }
});

We check if e.key is 's' to check if the S key is pressed.

And we check if the Ctrl or Command key is pressed with (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey).

We check if the code is run on a Mac with navigator.platform.match("Mac") and check the key pressed accordingly.

If both are true, we call e.preventDefault.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.