How to detect whether a control key is pressed and released from the keyboard?
“onkeydown” iam invoking the following function…and updating the flag “cntrl_key_pressed” to true and false accordingly.
onkeydown=“detectCTRLKey(event)”
function detectCTRLKey(e)
{
//alert(e);
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if(code==17)
cntrl_key_pressed=true;
}
how to identify that the control key is released from the keyboard, so that i can reset the flag (cntrl_key_pressed) to false.?
var cntrl_key_pressed=false;
function detectCTRLKey(e)
{
//alert(e);
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if(code==17)
{
cntrl_key_pressed=true;
alert("keydown event control key value :: "+cntrl_key_pressed);
}
}
function resetCTRLKey(e)
{
//var evt = e || window.event;
//alert(evt.type);
//alert('keyCode is ' + evt.keyCode);
//alert('charCode is ' + evt.charCode);
cntrl_key_pressed=false;
alert("keyup event control key value :: "+cntrl_key_pressed);
}
abhishek.c has an alternative that would work, although the detectCTRLKey function shold actually be called on mouseup. I’m not sure how much the cntrl_key_pressed is needed, as all the scripting can be done directly in the if(code==17) conditional.
The other alternative would be to trap the “ctrlKey” event property. It avoids having to use “keyCode” or “which”. There is a keydown and a keyup fork, as ctrlKey only gets triggered on keydown. Check out the source code below:
<input type=“text” id=“zorro” onkeydown=“checkKey(event);” onkeyup=“checkKey(event);” />
<script>
var theKeyPressed = null;
function checkKey(e) {
if(e.type == ‘keydown’) {
theKeyPressed = e.ctrlKey;
}
if(e.type == ‘keyup’ && theKeyPressed == true) {
return alert(‘the CTRL key has been released’);
}
}
</script>
In this case you are indeed better off using keycodes to detect and process multiple key characters, as follows:
<input type=“text” id=“zorro” onkeyup=“checkKey(event);” />
<script>
function checkKey(e) {
var theKeyPressed = null;
var reaction = false;