Remap the Control + S button in javascript (or jquery) - javascript

I've been having troubles with the Control + S button, I would like to remap the Control + S button to something else instead of the save page as window.
** I know that its not possible to disable it**
I want the functionality like what https://www.hastebin.com/ has, where if you control + s it does an action. I've already tried
$(window).keypress((e) => {
if (!(e.which == 115 && e.ctrlKey) && !(e.which == 19)) return true;
console.log('bruh');
e.preventDefault();
return false;
});
That DOES work, but the save as page still shows up, where as on hastebin, it does not when you do ctrl + S
Any ideas?

Use keydown rather than keypress:
$(window).on("keydown", (e) => {
if (e.key === "s" && e.ctrlKey) {
console.log("Ctrl+S");
e.preventDefault();
}
});
<div>Click here, then press Ctrl+S</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In that example I've used the key property rather than the deprecated which property, but if you need to support obsolete browsers you could use which (perhaps as a fallback).

CTRL+S fires keydown event, not keypress event AFAIK.
$(window).on("keydown", (e) => {
if (e.key === "s" && e.ctrlKey) e.preventDefault();
});

Related

React: Focus input on keyboard click (ctrl F / cmd F) instead of triggering Browser Search

Morning peeps,
I am trying to focus a search input in my application when someone presses CTRL+F or CMD+F instead of triggering the browser's search, and I would like to ask if that's even possible. An implementation that I found online but doesn't work obviously is this:
window.addEventListener('keydown', function (e) {
if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
if (document.getElementsById('search').not(':focus')) {
e.preventDefault();
console.log('Search is not in focus');
document.getElementsById('search').focus();
} else {
console.log('Default action of CtrlF');
return true;
}
}
});
I have also tried to use the useRef() from React in order to reach the input and focus it afterwards, but couldn't make it work. Any hints, ideas, code snippets that could help me?
change getElementsById to getElementById
use document.activeElement to check current focus element (much better approach)
Try this:
window.addEventListener('keydown', function (e) {
if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
if (document.getElementById('search') !== document.activeElement) {
e.preventDefault();
console.log('Search is not in focus');
document.getElementById('search').focus();
} else {
console.log('Default action of CtrlF');
return true;
}
}
});

Can I prevent ctrl + shift + p system print dialog on windows in the browser?

I would like to use the key combination ctrl + shift + p to open a command palette similar to how one opens on https://vscode.dev. This appears to work fine in browsers on MacOS, however when I try to do the same on windows it will open a system print dialog.
I have tried to add an event listener for 'beforeprint' but I don't believe it is cancellable.
window.addEventListener('beforeprint', (event) => {
event.preventDefault();
event.stopPropagation();
});
I'm trying to prevent the print dialog in this handler for the keybind
document.addEventListener('keydown', (event) => {
if (event.key === 'p' && event.shiftKey && (event.ctrlKey || event.metaKey)) {
// Prevent browser print dialog
event.preventDefault();
// Prevent dev tools command palette from opening
event.stopPropagation();
// Do logic here
}
});
This handler works seems to work fine on MacOS safari and chrome but I cannot replicate the behavior on Windows where it opens the system print dialog.
If you are using/can use jQuery:
$(document).bind("keyup keydown", function(e) {
if (e.ctrlKey && e.keyCode == 80) {
alert("Do what ever you want here.")
return false; // Stops print
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you run it here, it won't work. Try running it on codepen or somewhere else.
I was able to resolve this issue by switching my check for event.key === 'p' to event.keyCode === 80. I did not have any need for the 'beforePrint' handler.
document.addEventListener('keydown', (event) => {
if (event.keyCode === 80 && event.shiftKey && (event.ctrlKey || event.metaKey)) {
// Prevent browser print dialog
event.preventDefault();
// Prevent dev tools command palette from opening
event.stopPropagation();
// Do logic here
}
});

How to submit the form when pressing Ctrl + S (instead of "save the webpage") in JavaScript? [duplicate]

How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});

How to prevent default Shortcut alt+b by Firefox and IE via JS?

I need to implement a shortcut alt+b, calling a function. My problem is, that everytime i press this shortcut, a Firefox and an IE open a Menu-Bar "Edit". Is there any solution to prevent this default behavior? Or maybe it is possible to close this menu-bar after calling a function?
What i have tried but without success
$(document).keydown(function(e) {
if (e.keyCode == 18 || e.which==18)
{
e.preventDefault();
}
});
Try this, it will only run the console.log() if you hit Alt+B. Replace the console with anything you want.
$(window).keydown(function(event) {
if(event.altKey && event.keyCode == 66) {
event.preventDefault();
console.log("Hey! alt+B event captured!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This seems to work for me:
$(document).keydown(function(e) {
// check for alt+b
if (e.keyCode == 66 && e.altKey === true) {
e.preventDefault();
}
});
You need to check the press of b, not alt.

How do I capture a CTRL-S without jQuery or any other library?

How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});

Categories

Resources