| Next Tip?
Home » Javascript

Capturing CTRL+Keys using JavaScript

23 January 2009 173 views No Comment
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 4.00 out of 5)
Loading ... Loading ...

This is the practical scenario where sometime one wants to disallow Ctl+keys combinitions on web-pages.

Following Code-snippet tells the whole story:

<html>
<head>
<script language="JavaScript">
function testCtrlKeys(e)
{
//Create an array for all possible keys
var arrCtrlKeys = new Array('a', 'n', 'c', 'x', 'v', 'j');
var key;
var isCtrl;

if(window.event)
{
key = window.event.keyCode; //Valid only for Internet Explorer
if(window.event.ctrlKey)
isCtrl = true;
else
isCtrl = false;
}

else
{
key = e.which; //this is other than IE
if(e.ctrlKey)
isCtrl = true;
else
isCtrl = false;
}

//if ctrl is pressed check if other key is in forbidenKeys array
if(isCtrl)
{
for(i=0; i<arrCtrlKeys .length; i++)
{
//case-insensitive comparation
if(arrCtrlKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase())
{
alert('You have pressed CTRL + '
+String.fromCharCode(key)
+'.');

return false;
}
}
}
return true;
}
</script>

</head>
<body>
<form method="">
<div>
<h3>Test Key Combinition [Ctrl+A, Ctrl+N, Ctrl+C, Ctrl+X, Ctrl+V,Ctrl+J]</h3>
<input type="text" name="mytext"
onKeyPress="return testCtrlKeys(event);"
onKeyDown="return testCtrlKeys(event);" />
</div>
</body>
</html>

Note:
1. Copy/paste above code in text file and save it as “nameddoc.html” and run it into Explorer
2. Check the magic of capturing javascript keys.

Popularity: 3%

Post to Twitter Tweet This Post

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Ads by Lake Quincy Media

Leave your response!

You must be logged in to post a comment.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes