I want to save page changes when Ctrl-S or Ctrl-Enter is pressed
Ctrl-Enter works fine but on Ctrl-S I cannot prevent a Save dialog to appear.
$(document).on('keydown', function(e){
if (e.ctrlKey && (e.keyCode == 13 || e.keyCOde == 83)){
e.preventDefault();
// save data...
}
});
Any help?
Typo in your code
e.keyCOde == 83 ===> e.keyCode == 83 [Character "O" should be small]
This is what I use :
$(document).keydown(function(event) {
if (!((String.fromCharCode(event.which).toLowerCase() == 's' || event.keyCode == 13) && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-S pressed");
event.preventDefault();
return false;
});
Another choice is that you can use Shortcut library, you can enjoy more shortcut keys than just ctrl+s. Plus, this library has short & handy code as well :
shortcut.add("Ctrl+S",function() {
alert("Hi there!");
});
I want catch an event for Alt+c or something like that. My code is
html
<input type="text" id="name"/>
JavaScript
$("#name").keydown(function(e) {
if(e.keyCode == 67 && e.keyCode == 18){alert(e.keyCode);}
});
where is the problem? How it works on both Chrome & firefox?
You need to check for e.altKey instead:
if(e.altKey && e.keyCode == 67){alert(e.keyCode);}
Basically, you are checking for two codes as the same time. The event (e) has several values you can work with ... including altKey which is a boolean (true or false) ...
Try ... watching the e.altKey and the e.keyCode values.
$("#name").keydown(function(e) {
if(e.altKey && e.keyCode == 67) {
alert(e.keyCode);
}
});
With the right version of jQuery, there should be no issue between browsers.
$(document).keydown(function(e) {
//console.log(e.keyCode); If you want to check other keys code
if(e.keyCode == 67 || e.keyCode == 18){
console.log("alt or c pressed");
}
});
You can work around this to check if the two keys are pressed at the same time. I sujest you to use an aux var set to zero wich increase his value when keydown event triggered and decrease it when keyup.
Is it possible to set a default button for the ENTER key press for an entire webpage?
I googled and I came across the below code. But I'm not sure of what this line means var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode)); So I thought of posting this question here at stackoverflow.
Thanks.
<script language="javascript">
$(document).ready(function () {
$("input").bind("keydown", function (event) {
var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
if (keycode == 13) {
document.getElementById('btn').click();
return false;
} else {
return true;
}
});
});
</script>
Different browsers/devices1 support different properties of obtaining key codes. The ternary expression is the same as:
var keyCode;
if(event.keyCode) // if keyCode is supported get that #top-priority
keyCode = event.keyCode;
else if(event.which) // else, if .which is supported, get that
keyCode = event.which;
else // alas! nothing above is supported
keyCode = event.charCode; // we should take charCode
1 Devices for example EAN barcode reader has a charCode of 13 Since its .keyCode is 0 (falsy), the 1st if condition is failed. Courtesy - MLeFevre
With JQuery (if an option) I would do
$(document).keyup(function(evt) {
if (evt.keyCode == 13) {
// do your thing
}
}
This worked for me in Chrome,FF, Safari and Opera.
Also consider using various checks as in #Gaurang Tandon's answer to cover all hardware specs.
I am trying to figure out when a key press is an empty space, so I did the following:
if (e.which == ' '){
}
however this does not work. Any idea why?
event.which returns the code of the character pressed. space key code is 32, so use it instead:
if (e.which === 32) {
//
}
Another way is to convert character to char code with .charCodeAt():
if (e.which === " ".charCodeAt(0)) {
//
}
CHECK: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Write a test code and alert what the keyCode is.
document.onkeypress = function(e) {
e = e || window.event;
console.log(e.keyCode || e.which);
};
Learn to debug and you would not be asking these simple questions.
jQuery would have been
$(document).keypress(
function (e) {
console.log(e.which);
}
);
Probably this is what you're looking for: (Assuming you use the keydown event.)
if(e.keyCode == '32') {
// Your code
}
jsFiddle:
http://jsfiddle.net/DeHFL/
My users would like to be able to hit Ctrl+S to save a form. Is there a good cross-browser way of capturing the Ctrl+S key combination and submit my form?
App is built on Drupal, so jQuery is available.
This works for me (using jquery) to overload Ctrl+S, Ctrl+F and Ctrl+G:
$(window).bind('keydown', function(event) {
if (event.ctrlKey || event.metaKey) {
switch (String.fromCharCode(event.which).toLowerCase()) {
case 's':
event.preventDefault();
alert('ctrl-s');
break;
case 'f':
event.preventDefault();
alert('ctrl-f');
break;
case 'g':
event.preventDefault();
alert('ctrl-g');
break;
}
}
});
$(window).keypress(function(event) {
if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-S pressed");
event.preventDefault();
return false;
});
Key codes can differ between browsers, so you may need to check for more than just 115.
You could use a shortcut library to handle the browser specific stuff.
shortcut.add("Ctrl+S",function() {
alert("Hi there!");
});
This jQuery solution works for me in Chrome and Firefox, for both Ctrl+S and Cmd+S.
$(document).keydown(function(e) {
var key = undefined;
var possible = [ e.key, e.keyIdentifier, e.keyCode, e.which ];
while (key === undefined && possible.length > 0)
{
key = possible.pop();
}
if (key && (key == '115' || key == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))
{
e.preventDefault();
alert("Ctrl-s pressed");
return false;
}
return true;
});
This one worked for me on Chrome...
for some reason event.which returns a capital S (83) for me, not sure why (regardless of the caps lock state) so I used fromCharCode and toLowerCase just to be on the safe side
$(document).keydown(function(event) {
//19 for Mac Command+S
if (!( String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-s pressed");
event.preventDefault();
return false;
});
If anyone knows why I get 83 and not 115, I will be happy to hear, also if anyone tests this on other browsers I'll be happy to hear if it works or not
I combined a few options to support FireFox, IE and Chrome. I've also updated it to better support mac
// simply disables save event for chrome
$(window).keypress(function (event) {
if (!(event.which == 115 && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) && !(event.which == 19)) return true;
event.preventDefault();
return false;
});
// used to process the cmd+s and ctrl+s events
$(document).keydown(function (event) {
if (event.which == 83 && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {
event.preventDefault();
save(event);
return false;
}
});
$(document).keydown(function(e) {
if ((e.key == 's' || e.key == 'S' ) && (e.ctrlKey || e.metaKey))
{
e.preventDefault();
alert("Ctrl-s pressed");
return false;
}
return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try pressing ctrl+s somewhere.
This is an up-to-date version of #AlanBellows's answer, replacing which with key. It also works even with Chrome's capital key glitch (where if you press Ctrl+S it sends capital S instead of s). Works in all modern browsers.
I would like Web applications to not override my default shortcut keys, honestly. Ctrl+S already does something in browsers. Having that change abruptly depending on the site I'm viewing is disruptive and frustrating, not to mention often buggy. I've had sites hijack Ctrl+Tab because it looked the same as Ctrl+I, both ruining my work on the site and preventing me from switching tabs as usual.
If you want shortcut keys, use the accesskey attribute. Please don't break existing browser functionality.
#Eevee: As the browser becomes the home for richer and richer functionality and starts to replace desktop apps, it's just not going to be an option to forgo the use of keyboard shortcuts. Gmail's rich and intuitive set of keyboard commands was instrumental in my willingness to abandon Outlook. The keyboard shortcuts in Todoist, Google Reader, and Google Calendar all make my life much, much easier on a daily basis.
Developers should definitely be careful not to override keystrokes that already have a meaning in the browser. For example, the WMD textbox I'm typing into inexplicably interprets Ctrl+Del as "Blockquote" rather than "delete word forward". I'm curious if there's a standard list somewhere of "browser-safe" shortcuts that site developers can use and that browsers will commit to staying away from in future versions.
To Alan Bellows answer: !(e.altKey) added for users who use AltGr when typing (e.g Poland). Without this pressing AltGr+S will give same result as Ctrl+S
$(document).keydown(function(e) {
if ((e.which == '115' || e.which == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))
{
e.preventDefault();
alert("Ctrl-s pressed");
return false;
}
return true; });
I like this little plugin. It needs a bit more cross browser friendliness though.
This should work (adapted from https://stackoverflow.com/a/8285722/388902).
var ctrl_down = false;
var ctrl_key = 17;
var s_key = 83;
$(document).keydown(function(e) {
if (e.keyCode == ctrl_key) ctrl_down = true;
}).keyup(function(e) {
if (e.keyCode == ctrl_key) ctrl_down = false;
});
$(document).keydown(function(e) {
if (ctrl_down && (e.keyCode == s_key)) {
alert('Ctrl-s pressed');
// Your code
return false;
}
});
example:
shortcut.add("Ctrl+c",function() {
alert('Ok...');
}
,{
'type':'keydown',
'propagate':false,
'target':document
});
usage
<script type="text/javascript" src="js/shortcut.js"></script>
link for download: http://www.openjs.com/scripts/events/keyboard_shortcuts/#
This Plugin Made by me may be helpful.
Plugin
You can use this plugin you have to supply the key Codes and function to be run like this
simulatorControl([17,83], function(){
console.log('You have pressed Ctrl+Z');
});
In the code i have displayed how to perform for Ctrl+S. You will get Detailed Documentation On the link. Plugin is in JavaScript Code section Of my Pen on Codepen.
I solved my problem on IE, using an alert("With a message") to prevent default Behavior:
window.addEventListener("keydown", function (e) {
if(e.ctrlKey || e.metaKey){
e.preventDefault(); //Good browsers
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { //hack for ie
alert("Please, use the print button located on the top bar");
return;
}
}
});
This was my solution, which is much easier to read than other suggestions here, can easily include other key combinations, and has been tested on IE, Chrome, and Firefox:
$(window).keydown(function(evt) {
var key = String.fromCharCode(evt.keyCode).toLowerCase();
switch(key) {
case "s":
if(evt.ctrlKey || evt.metaKey) {
fnToRun();
evt.preventDefault(true);
return false;
}
break;
}
return true;
});
A lot of answers in this thread mention e.which or e.Keycode which are not recommended nowadays according to MDN and https://keyjs.dev/. Moreover, the most-rated answer looks a little bit overdone since it also brings other hotkeys which leads to usage of switch. I did not check the third-party libraries, but I always try to use as few third-party libraries as possible.
Here's my solution (since you mentioned jQuery in your question):
$(document).keydown(function(e) {
if (e.ctrlKey && e.key == "s" || e.metaKey && e.key == "s") {
myFunction();
e.preventDefault();
}
});
The e.metaKey is here because of Mac devices.
The myFunction(); line is where you specify your function. The e.preventDefault(); line is here to prevent opening of the "Saveā¦" window. If you want to keep it for some reason, feel free to remove this line.