<html>
<head>
<script>
// setup global variables for use through the code..
var distance_x = 3;
var distance_y = 3;
var screen_top = 10;
var screen_left = 10;
var screen_height = 300;
var screen_width = 500;
if(window.Event){ // cature keypresses..
document.captureEvents(Event.KEYDOWN); document.onkeydown = setkey;
}else{
document.onkeydown = function(){
return setkey(event);
}
}
function setkey(event){ // what to do each time a key is pressed..
var obj = document.getElementById('ananything');
obj.x = parseInt(obj.style.left); // get the objects X position
obj.y = parseInt(obj.style.top); // get the objects Y position
obj.w = parseInt(obj.offsetWidth); // get the objects width
obj.h = parseInt(obj.offsetHeight); // get the objects height
// alert(event.which); // use this to find out what key is pressed
if((event.which==13)||(event.keyCode==13)){
alert("You have pressed the enter key");
}
if((event.which==37)||(event.keyCode==37)){ obj.x = obj.x - distance_x; } // left
if((event.which==39)||(event.keyCode==39)){ obj.x = obj.x + distance_x; } // right
if((event.which==38)||(event.keyCode==38)){ obj.y = obj.y - distance_y; } // up
if((event.which==40)||(event.keyCode==40)){ obj.y = obj.y + distance_y; } // down
if((obj.y >= screen_top)&&(obj.y<= screen_top+screen_height-obj.h)){ obj.style.top = obj.y;} // update Y position..
if((obj.x >= screen_left)&&(obj.x<= screen_left+screen_width-obj.w)){ obj.style.left = obj.x;} // update X position..
document.title = obj.x + "x" + obj.y + " / " + obj.w + "x" + obj.h; // show this in the title bar
}
function setup(){ // set starting opsition of objects
document.getElementById('ananything').style.left=300;
document.getElementById('ananything').style.top=100;
}
</script>
<style>
#ananything{position:absolute;background:skyblue;color:lightgreen;}
#area{position:absolute;left:10px;top:10px;width:500px;height:300px;background:green;}
</style>
</head>
<body onLoad="setup()">
This is the webpage, I encourage you to type something
<div id="area">
</div>
<div id="ananything">
hello
</div>
</body>
</html>