Disable ctrl + n and other ctrl + key combinations in JavaScript


Few days ago Vijay asked if there’s a way to disable ctrl + n combination (open the new window shortcut. So I set out to create a small Java Script that disables any ctrl + key combination (e.g. ctrl + v, ctrl + c, ctrl + a, etc.).

Script is a bit more complicated than Disable form submit on enter keypress and it should work in both Fire Fox and Internet Explorer.

1 <script language="JavaScript">
2 function disableCtrlKeyCombination(e)
3 {
4     //list all CTRL + key combinations you want to disable
5     var forbiddenKeys = new Array('a''n''c''x''v''j');
6     var key;
7     var isCtrl;
8
9     if(window.event)
10     {
11         key = window.event.keyCode;     //IE
12         if(window.event.ctrlKey)
13                         isCtrl = true;
14                 else
15                         isCtrl = false;
16     }
17     else
18     {
19         key = e.which;     //firefox
20         if(e.ctrlKey)
21             isCtrl = true;
22         else
23             isCtrl = false;
24     }
25
26     //if ctrl is pressed check if other key is in forbidenKeys array
27     if(isCtrl)
28     {
29         for(i=0; i<forbiddenkeys .length; i++)
30         {
31             //case-insensitive comparation
32             if(forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase())
33             {
34                 alert('Key combination CTRL + '
35                     +String.fromCharCode(key)
36                     +' has been disabled.');
37                 return false;
38             }
39         }
40     }
41     return true;
42 }
43 </script>

And you just add this to the field where you’d like to disable keys:

1 <input type="text" name="mytext"
2     onKeyPress="return disableCtrlKeyCombination(event);"
3     onKeyDown="return disableCtrlKeyCombination(event);" />

Although the key combinations are disabled only on one field the same script can be easily modified to disable ctrl + key combinations on whole page.

Also if you are looking for something more sophisticated and with more features you might want to take a look at a visitor comment that contains DisableKeys.js script that gives you more control and you can disable almost any key and/or key combination, including ctrl + key and alt + key.

Copy from http://www.arraystudio.com/as-workshop/disable-ctrl-n-and-other-ctrl-key-combinations-in-javascript.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s