Track keys pressed

[Total: 0    Average: 0/5]

This example shows how to have IE and NS monitor for key presses.

Body Code:

H to move Negative
<BR>
L to move Positive
<BR>
<form name=exf1>
<input type=text name=x value="100">
</form>

<script>
var KEY_LEFT  = "h"; // vi left key
var KEY_RIGHT = "l"; // vi right key
var STOP_KEY  = " "; // space
var UNIT_VECTOR  = 5; // 5 pixel is a unit vector
var LEFT_VECTOR  = -1 * UNIT_VECTOR; // negative 1 unit vector
var RIGHT_VECTOR = 1  * UNIT_VECTOR; // positive 1 unit vector
var STOP_VECTOR  = 0  * UNIT_VECTOR; // zero unit vector
var moveDistance = STOP_VECTOR;  // dont' move at the start.
var DELAY = 50; // 50 milliseconds between movements.
var isIE=document.all?true:false;
var isNS=document.layers?true:false;
function moveLeft()  { moveDistance = LEFT_VECTOR;  }
function moveRight() { moveDistance = RIGHT_VECTOR; }
function stopMove()  { moveDistance = STOP_VECTOR;  }
document.onkeypress=keyhit;
function keyhit(e) {
  if (isIE) {
    if (String.fromCharCode(event.keyCode) == KEY_LEFT)  moveLeft();
    if (String.fromCharCode(event.keyCode) == KEY_RIGHT) moveRight();  
    if (String.fromCharCode(event.keyCode) == STOP_KEY)  stopMove();
  }
  if (isNS) {
    if (String.fromCharCode(e.which) == KEY_LEFT)  moveLeft();
    if (String.fromCharCode(e.which) == KEY_RIGHT) moveRight();
    if (String.fromCharCode(e.which) == STOP_KEY)  stopMove();
  }
}
function updatePosition() {
  document.exf1.x.value = parseInt(moveDistance) + parseInt(document.exf1.x.value);
}
function startIt() {
  setInterval("updatePosition()",DELAY);
}
</script>
<a href="javascript:startIt()">start it</a>

Times Viewed: 0

Leave a Reply

Your email address will not be published. Required fields are marked *