Ok so I made a page that can move an image with the arrow keys but only the down and right functions work. I made the functions from a hide show script because i’m very new to javascript.
Here is the code.
left
function left(id) {
var y = '5';
var z =document.getElementById(id).style.left;
var x = parseInt(y)+parseInt(z);
var state = document.getElementById(id).style.left;
if (state == '1') {
document.getElementById(id).style.left = x;
} else {
document.getElementById(id).style.left = x;
}
}
right
function right(id) {
var y = '5';
var z =document.getElementById(id).style.right;
var x = parseInt(y)+parseInt(z);
var state = document.getElementById(id).style.right;
if (state == '1') {
document.getElementById(id).style.right = x;
} else {
document.getElementById(id).style.right = x;
}
}
up
function up(id) {
var y = '5';
var z =document.getElementById(id).style.bottom;
var x = parseInt(y)+parseInt(z);
var state = document.getElementById(id).style.bottom;
if (state == '1') {
document.getElementById(id).style.bottom = x;
} else {
document.getElementById(id).style.bottom = x;
}
}
down
function down(id) {
var y = '5';
var z =document.getElementById(id).style.top;
var x = parseInt(y)+parseInt(z);
var state = document.getElementById(id).style.top;
if (state == '1') {
document.getElementById(id).style.top = x;
} else {
document.getElementById(id).style.top = x;
}
}
then the arrow key script
document.onkeyup = KeyCheck;
function KeyCheck() {
var KeyID = event.keyCode;
switch(KeyID)
{
case 37:
right('img');
break;
case 38:
up('img')
break
case 39:
left('img');
break;
case 40:
down('img');
break;
}
}
and then the html
<img id="img" src="http://trevorrudolph.com/logo.png" style="position:absolute; left:1; bottom:1; right:1; top:1;">
you can download the html at arrow.zip
the actual page is here
You should only be positioning it with
topandleft, because if you try to do it the way you’re doing it, you are going to end up with very messed up properties, such as atopof say 5 but abottomof say 100.Also, you should use a unit, preferable pixels, for the
topandleftproperties.So, all you really need to do is change your functions to look like:
Also, you should be using
<script type="text/javascript">instead of<script language="JavaScript">. The latter form is deprecated.