|
| Input Functions
This week, we will be mostly covering...
...Controlling JS with the Mouse and Keyboard.
Keyboard, mouse and event control can be very complicated. Fortunately, I have created some functions which convert events such as mouse movement and key presses into variables which can be accessed at any time.
Before you can use the mouse and keyboard for control, you need to assign functions to certain event handlers -
<body onMousemove="eHandle();" onMousedown="eHandle();" onMouseup="eHandle('mouseup');" onMousewheel="eHandle();" onKeydown="eHandle();" onKeyup="eHandle('keyup');">
Variables are set up to hold the values recovered by each function call -
var mTimer, mouseX, mouseY, mButs, wheel, keyB, keys;
mouseX=0;
mouseY=0;
mButs=0;
wheel=0;
keyB=0;
var kys=new Array("None pressed","","","","","","","","Backspace","Tab","","","","Enter","","","Shift","Control","Alt","Pause/Break","Caps Lock","","","","","","","Esc","","","","","Space Bar","Page Up","Page Down","End","Home","Left","Up","Right","Down","","","","","Insert","Delete","","0","1","2","3","4","5","6","7","8","9","","","","","","","","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","Windows","","Menu","","","0","1","2","3","4","5","6","7","8","9","*","+","","-",".","/","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12","","","","","","","","","","","","","","","","","","","","","Num Lock","Scroll Lock","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",";","=",",","-",".","","\'","","","","","","","","","","","","","","","","","","","","","","","","","","","[","\\","]","#","¬");
keys=new Array();
keys.length=kys.length;
for(i=0;i<keys.length;i++){keys[i]=0;}
These variables hold the following data:
| Variable | Data |
| mouseX | The horizontal (X coordinate) position of the cursor. |
| mouseY | The vertical (Y coordinate) position of the cursor. |
| mButs | A numerical value unique to the combination of mouse buttons pressed. |
| wheel | The direction the mouse wheel was last turned. (MSIE 6+) |
| keyB | The last key pressed on the keyboard. |
| keys | An array holding a record of which keys are currently held down. |
| kys | An array holding text values relating to each key. |
The function which controls these variables is the eHandle() function-
function eHandle(et){
eType=et;
mouseX=event.clientX+document.body.scrollLeft;
mouseY=event.clientY+document.body.scrollTop;
mButs=event.button;
wheel+=event.wheelDelta/120;
var ky=event.keyCode;
keyB=ky
keys[ky]=1;
switch(eType){
case "mouseup":
mButs=0;
break;
case "keyup":
keyB=0;
keys[ky]=0;
break;
}
}
Now that we have a function which can turn the event object into a group of useful variables, we need a practical example of how to use them.
|