Friday, January 23, 2009

Capturing CTRL+Keys using JavaScript

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.

No comments:

Post a Comment