How to Disable the CTRL+P using javascript or Jquery? - javascript

Here I tried to disable the Ctrl+P but it doesn't get me alert and also it shows the print options
jQuery(document).bind("keyup keydown", function(e){
if(e.ctrlKey && e.keyCode == 80){
alert('fine');
return false;
}
});
http://jsfiddle.net/qaapD/10/
I am not sure how can I disable the Ctrl+P combination itself using jQuery or JavaScript.
Thanks

You can't prevent the user from printing, but you can hide everything when the user prints the document by using simple CSS:
<style type="text/css" media="print">
* { display: none; }
</style>
Updated fiddle.
If you would like to show the visitor a custom message when he/she try to print rather then just a blank page, it's possible with client side code but first wrap all your existing contents like this:
<div id="AllContent">
<!-- all content here -->
</div>
And add such a container with the custom message:
<div class="PrintMessage">You are not authorized to print this document</div>
Now get rid of the <style type="text/css" media="print"> block and the code would be:
if ('matchMedia' in window) {
// Chrome, Firefox, and IE 10 support mediaMatch listeners
window.matchMedia('print').addListener(function(media) {
if (media.matches) {
beforePrint();
} else {
// Fires immediately, so wait for the first mouse movement
$(document).one('mouseover', afterPrint);
}
});
} else {
// IE and Firefox fire before/after events
$(window).on('beforeprint', beforePrint);
$(window).on('afterprint', afterPrint);
}
function beforePrint() {
$("#AllContent").hide();
$(".PrintMessage").show();
}
function afterPrint() {
$(".PrintMessage").hide();
$("#AllContent").show();
}
Code is adopted from this excellent answer.
Updated fiddle. (showing message when printing)

After much testings on various browsers, it is easier to intercept the keys when they are down (not pressed) because some of this "App integrated keys" are difficult to intercept with the "keypress" event.
I came up with this script that is sort of cross browser compatible (I didn't test for Microsoft's IE). Notice that the browsers return different codes for some keys. In my case I wanted to prevent Ctrl+P.
The key "P" on chrome is seen as e.keyCode == 80, on opera, it is e.charCode == 16, while on firefox it is e.charCode == 112
$(document).on('keydown', function(e) {
if((e.ctrlKey || e.metaKey) && (e.key == "p" || e.charCode == 16 || e.charCode == 112 || e.keyCode == 80) ){
alert("Please use the Print PDF button below for a better rendering on the document");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
});
I used jQuery.

This is basically Peters answer from above. The difference is I added the accountability for mac when pressing the cmd+p button combo to print a page.
$(document).on('keydown', function(e) {
if((e.ctrlKey || e.metaKey) && (e.key == "p" || e.charCode == 16 || e.charCode == 112 || e.keyCode == 80) ){
alert("Please use the Print PDF button below for a better rendering on the document");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
});

To disable Ctrl+P printing by using javascript use below code:
window.addEventListener('keydown', function(event) {
if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
event.preventDefault();
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
event.stopPropagation();
}
return;
}
}, true);

Your code works in the jsfiddle example? What browser are you using? Itested it with the latest chrome and it worked fine.
You can also add:
e.preventDefault();

This Actually worked for me in chrome. I was pretty suprised.
jQuery(document).bind("keyup keydown", function(e){
if(e.ctrlKey && e.keyCode == 80){
Print(); e.preventDefault();
}
});
Where Print is a function I wrote that calls window.print(); It also works as a pure blocker if you disable Print();
As noted here: https://stackoverflow.com/a/20121038/2102085
window.print() will pause so you can add an onPrintFinish or onPrintBegin like this
function Print(){
onPrintBegin
window.print();
onPrintFinish();
}
(Again this is just chrome, but Peter has a downvoted solution below that claims the keycodes are different for ff and ie)

had a journy finding this, should be canceled on the keydown event
document.addEventListener('keydown',function(e){
e.preventDefault();
return false;
});
further simplified to :
document.onkeydown = function(e){
e.preventDefault();
}
given you have only one keydown event

there are some shortcuts you simply can't override with javascript, i learned it the hard way. I suppose CTRL+P is one of them.
one way to override them would be to deploy a chrome pacakged app.

Try this
//hide body on Ctrl + P
jQuery(document).bind("keyup keydown", function (e) {
if (e.ctrlKey && e.keyCode == 80) {
$("body").hide();
return false;
}
});

Here is the code, it work for me
document.addEventListener("keydown", function(event) {
if (event.ctrlKey && event.key === "p") {
event.preventDefault();
}
});

<script>
function isKeyPressed(event)
{
if(event.ctrlKey == 1)
{
alert("Please Submit exam form befor printing");
}
}
</script>
<body onkeydown="isKeyPressed(event)">
<p>this is the solution</p>
</body>

If you want to disable printing of your webpage you're wasting your time: it can't be done. Even if you work out how to capture CTRL-P users can still use the browsers menu bar to find the print command, or they can take a screen shot of the browser.
Stop trying to control the user, put your energy into making your site / app more useful, not less useful.
edit 2016: in the 3 years this has been up it has gathered 3 downvotes. I'm still not deleting it. I think it is important to tell fellow developers when they are given impossible tasks, or tasks that make no sense.
edit 2018: still think it's important that people that have this question read this answer.

Related

How to disable View source and inspect element

How do you disable/ view source/ and /inspect element/, ctrl + u ctrl+shift+I f12 menu bar and right click, also ctrl + s ctrl p ctrl+v ctrl+a ctrl+c and drag select page, please answer all parts that's possible, I prefer to do this will JavaScript array keycodes or html no php or other languages.also I want to block ifram use on my site like somesites such as google.
As I understand it is not possible to completely disable view source and inspect element, so I want minification of code and rest of my question answered instead.
Edit:
I solved alot of it myself, I used onkeydown return false to disable all keys, still need the arrays, I disabled inspect element menu bar by forcing browser to window.open I still need right click, however would like to add that I need a custom right click menu, I disabled the possibility to disable Javascript in order to stop the key block by using noscript function redirects. I also still need the drag and select part. I would still like betterways to fix it...maybe even just minify the code or encrypt it. Of anyone needs some of the code I used just reply. I just need to fix it.
It is not possible to prevent the user from inspecting code running on their machine. At the end of the day the HTMl they are getting delivered will be readable in plain text. You can cause a nuisance for most people, but this will not be a valid security measure - chrome extensions will still run, for instance, so if someone is using the NoScript extension it will disable all javascript.
A much better option would be to handle your logic serverside, and only send the client the information they need to know/requested.
There are some free javascript obfuscators, such as https://javascriptobfuscator.com/. Please remember that it is not a secure method, though.
I mean no matter how much you block it a person can just type
view-source:https://example.com
document.onkeydown = function(e)
{
if(event.keyCode == 123)
{
return false;
}
if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0))
{
return false;
}
if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0))
{
return false;
}
if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0))
{
return false;
}
if(e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0))
{
return false;
}
}
e is a keyboard event. e.[key] returnes true if key pressed.
If document.onkeydown returns false, key doesn't count.
This programm seeing if code view combination pressed and returning false.
Example. if ctrl, shift and 'J' pressed - return false.
Bump
To the people saying it isn't possible, how would you recon this website managed to do so?
The following website disabled, view source, right click and the dev console.
I am genuinely interested.
https://www.techgyd.com/contact-facebook-directly/6579/
Edit:
all input from keyboard is disabled, but by adding "view-source:" before the httpps:// to the url to become:
view-source:https://www.techgyd.com/contact-facebook-directly/6579/
makes me able to see.
If you would like to know how they did that then take a look at their JS, raw copy/paste:
<script type="text/javascript">
//<![CDATA[
var show_msg = '';
if (show_msg !== '0') {
var options = {view_src: "View Source is disabled!", inspect_elem: "Inspect Element is disabled!", right_click: "Right click is disabled!", copy_cut_paste_content: "Cut/Copy/Paste is disabled!", image_drop: "Image Drag-n-Drop is disabled!" }
} else {
var options = '';
}
function nocontextmenu(e) { return false; }
document.oncontextmenu = nocontextmenu;
document.ondragstart = function() { return false;}
document.onmousedown = function (event) {
event = (event || window.event);
if (event.keyCode === 123) {
if (show_msg !== '0') {show_toast('inspect_elem');}
return false;
}
}
document.onkeydown = function (event) {
event = (event || window.event);
//alert(event.keyCode); return false;
if (event.keyCode === 123 ||
event.ctrlKey && event.shiftKey && event.keyCode === 73 ||
event.ctrlKey && event.shiftKey && event.keyCode === 75) {
if (show_msg !== '0') {show_toast('inspect_elem');}
return false;
}
if (event.ctrlKey && event.keyCode === 85) {
if (show_msg !== '0') {show_toast('view_src');}
return false;
}
}
function addMultiEventListener(element, eventNames, listener) {
var events = eventNames.split(' ');
for (var i = 0, iLen = events.length; i < iLen; i++) {
element.addEventListener(events[i], function (e) {
e.preventDefault();
if (show_msg !== '0') {
show_toast(listener);
}
});
}
}
addMultiEventListener(document, 'contextmenu', 'right_click');
addMultiEventListener(document, 'cut copy paste print', 'copy_cut_paste_content');
addMultiEventListener(document, 'drag drop', 'image_drop');
function show_toast(text) {
var x = document.getElementById("amm_drcfw_toast_msg");
x.innerHTML = eval('options.' + text);
x.className = "show";
setTimeout(function () {
x.className = x.className.replace("show", "")
}, 3000);
}
//]]>
</script>
or just look from line 86
I hope it helps

Keyboard shortcut ctrl+r not working for me

In the snippet below, Ctrl+Enter (event.which == 13) is working. However, Ctrl+R (event.which == 9) is not.
if ($('.selector')) {
$(document).keypress(function(event) {
if ( event.altKey && event.which == 13 ) {
$('.link a').trigger('click');
} else if ( event.altKey && event.which == 82 ) {
$('.link a').trigger('click');
} else {
return false;
}
});
}
The problem with your code is the keyPress listener behaves differently and uses a different set of keyCode. For keyPress the r key is 114 while for keyDown it is 82.
Also another problem is browser's default reload function will override your function because keypress is executed after you release the key. To solve this, change keypress to keydown.
$(document).keydown(function(e){
if(e.which === 82 && e.ctrlKey){ //keycode is 82 for keydown
alert("Pressed!");
e.preventDefault(); //stop browser from reloading
}
});
http://jsfiddle.net/DerekL/3P9NS/show
PS: It seems like Firefox is ignoring e.preventDefault (which by W3C standards it should). The best thing to do to support all browsers is to choose another combination, or use ctrl + alt + r.
if(e.which === 82 && e.ctrlKey && e.altKey){
Based on some quick testing at http://api.jquery.com/event.which/, it seems you want event.which == 82, not event.which == 9. Although most browsers tend to use Ctrl + R to refresh the page, so this might not be the best way to handle whatever you're doing.
A cross-Browser solution to prevent Ctrl+R refresh page:
LIVE DEMO (works in Firefox, Chrome, Safari, Opera)
var keyEv = navigator.userAgent.indexOf('Firefox')>-1?["keypress",114]:["keydown",82];
$(document)[keyEv[0]](function(e) {
if ( e.ctrlKey && e.which == keyEv[1] ){
e.preventDefault();
alert("CTRL+R");
}
});
By simply testing for our navigator.userAgent you can decide what Key event listener to use and the respective R key code.
If you need to handle both R and ENTER in combination with Ctrl than you just need this little tweak:
LIVE DEMO (again all browsers :) )
var keyEv = navigator.userAgent.indexOf('Firefox')>-1?["keypress",114]:["keydown",82];
$(document)[keyEv[0]](function(e) {
var k = e.which;
if ( e.ctrlKey && k==keyEv[1] || k==13 ){ // no XBrowser issues with 13(Enter)
// so go for it!
e.preventDefault();
alert("Do something here");
}
});

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.
You don't need any of those libraries, just try this:
$(document).on('keydown', function(e){
if(e.ctrlKey && e.which === 83){ // Check for the Ctrl key being pressed, and if the key = [S] (83)
console.log('Ctrl+S!');
e.preventDefault();
return false;
}
});
The problem was that your code halted at the alert(), preventing your function from interrupting the save dialogue.
(Still uses jQuery)
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);
People are still viewing this it seems, so it's probably worth pointing out that there is no need for jQuery on this one, here:
function keydown (event) {
var isCtrlKeyDown = navigator.platform.indexOf("Mac") > -1 ? event.metaKey : event.ctrlKey,
isSDown = (event.key && event.key === "s") || (event.keyCode || event.which) === 83 // falls back to keycode if no event.key
if (isCtrlKeyDown && isSDown) {
// prevent default event on newer browsers
if (event.preventDefault) {
event.preventDefault()
}
// ... your code here ...
// prevent default event on older browsers
return false
}
}
// register the event
if (document.addEventListener) {
document.addEventListener("keydown", keydown)
} else {
document.onkeydown = keydown
}
That should work in all browsers, this will also work for folks using alternative keyboard layouts from QWERTY on Windows, which reports incorrect key codes (at least on Chrome 56 on Windows 10 in my testing)
However, this looks kind of clunky, and confusing, so if you are only supporting modern browsers, you can do the following instead:
document.addEventListener("keydown", function keydown (event) {
if (navigator.platform === "MacIntel" ? event.metaKey : event.ctrlKey && event.key === "s") {
event.preventDefault()
// ... your code here ...
}
})
As of 2017, instead of using e.keyCode === 83 you should use e.key === 's' as the former is deprecated.
No need to use any plugin, just use below jquery code
$(document).bind('keydown', 'ctrl+s', function (e) {
if (e.ctrlKey && (e.which == 83)) {
e.preventDefault();
//Your method()
return false;
}
});
Since you are using alert, the execution halts at the alert and "return false" is not executed until you close the alertbox, thats the reason you see the default dialog.
If your method is long running better use asyn method method instead.

How can I disabling backspace key press on all browsers?

I'm trying to disable the backspace button on an order page in all cases except when a textarea or text input is an active element to prevent users from accidentally backing out of an order. I have it working fine in most browsers, but in IE (testing in IE9, both regular and compatibility mode) it still allows the user to hit the backspace and go to the previous page.
Here's the code:
$(document).keypress(function(e){
var activeNodeName=document.activeElement.nodeName;
var activeElType=document.activeElement.type;
if (e.keyCode==8 && activeNodeName != 'INPUT' && activeNodeName != 'TEXTAREA'){
return false;
} else {
if (e.keyCode==8 && activeNodeName=='INPUT' && activeElType != 'TEXT' && activeElType != 'text'){
return false;
}
}
});
Any advice on what I'm doing wrong here?
Thanks!
I think you're overcomplicating that. Rather than checking for an active element, find the event target instead. This should give you the information you need. It's also better to use keydown rather than keypress when there is no visible character. Finally, it's better to use e.preventDefault() for better granularity.
$(document).keydown(function(e) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.which === 8) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
NB I could have done this the other way round, rather than an empty if block and all the code going in the else block, but I think this is more readable.
Instead of keypress, try the keydown function, it will fire before the actual browser based hook. Also, putting in a preventDefault() function will assist in this. IE :
$(document).keydown(function(e){
e.preventDefault();
alert(e.keyCode);
});
Hope this helps.
The most Simple thing you can do is add the following one line in the very first script of you page at very first line
window.history.forward(1);
Most examples seem to be for the JQuery framework - Here an example for ExtJS
(I've been getting a lot of downvotes for this recently as the question now has JQuery tag on it, which it didn't previously. I can remove the answer if you like as isn't for JQuery but it's proven to help others not using that framework).
To use this add this code block to your code base, I recommend adding it inside the applications init function().
/**
* This disables the backspace key in all browsers by listening for it on the keydown press and completely
* preventing any actions if it is not which the event fired from is one of the extjs nodes that it should affect
*/
Ext.EventManager.on(window, 'keydown', function(e, t) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.getKey() == e.BACKSPACE) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
Use e.which instead of e.keyCode; jQuery normalizes this value across browsers.
http://api.jquery.com/keydown/
To determine which key was pressed,
examine the event object that is
passed to the handler function. While
browsers use differing properties to
store this information, jQuery
normalizes the .which property so you
can reliably use it to retrieve the
key code.
Then, use e.preventDefault(); to prevent the default behaviour of moving to the previous page.
<html>
<head>
<script type="text/javascript">
function stopKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 8) && (node.type!="text")) {return false;}
}
document.onkeypress = stopKey;
</script>
</head>
<body onkeydown="return stopKey()">
<form>
<input type="TEXTAREA" name="var1" >
<input type="TEXT" name="var2" >
</form>
</body>
</html
I had to add the onDownKey attribute to the body in order to get editing keys to go to the functions.
$(document).keydown(function(e) {
var elid = $(document.activeElement).is('input');
if (e.keyCode === 8 && !elid) {
return false;
}
});
Hope this might help you
Seems like the "backspace" will also act as "navigation back" if you have selected radio buttons, check-boxes and body of document as well. Really annoying for forms - especially when using post. All the form could be lost with one slip of the "backspace" key -_- ...
Honestly... who's idea was it to allow the "backspace as a navigational "back" button!!! really bad idea in my opinion.
I disable the "backspace" default on anything that is not a text area or text field - like this:
$(document).keydown(function(e){
console.log(e.keyCode+"\n");
var typeName = e.target.type;//typeName should end up being things like 'text', 'textarea', 'radio', 'undefined' etc.
console.log(typeName+"\n");
// Prevent Backspace as navigation backbutton
if(e.keyCode == 8 && typeName != "text" && typeName != "textarea"){
console.log("Prevent Backbutton as Navigation Back"+typeName+"\n");
e.preventDefault();
}
//
})
Not sure where else one would want the normal behavior of a back-button other than in these two areas.
document.onkeydown = KeyPress;
function KeyPress(e) {
if (!e.metaKey){
e.preventDefault();
}
}

Best cross-browser method to capture CTRL+S with JQuery?

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.

Categories