...

View Full Version : Use keyboard to move a div



Pythondev
10-31-2006, 11:19 PM
I want to have a small div on my page which can be moved around using the keys on the keyboard.


So if you press up the div moves up 5px. Down it moves down 5px. Left it moves left 5px. Right it moves right 5px.


Ok, I have been able to get it working fine in IE but cant get it to work in Firefox...

This is what I have...


<HTML>
<HEAD>
<TITLE>Cursor Mover</TITLE>
<SCRIPT>
function move()
{
ek = window.event.keyCode;
if (ek==37) DIV1.style.posLeft-=5;
if (ek==39) DIV1.style.posLeft+=5;
if (ek==38) DIV1.style.posTop-=5;
if (ek==40) DIV1.style.posTop+=5;
}

</SCRIPT>
</HEAD>
<BODY onkeydown="move();">
<DIV ID="DIV1" style="position:absolute;top:100;left:100;height:20;width:20;background-color:#000000;"></DIV>
</BODY>
</HTML>

How can I get it to work?
Thanks

Basscyst
11-01-2006, 01:15 AM
Here ya go:



<HTML>
<HEAD>
<TITLE>Cursor Mover</TITLE>
<SCRIPT>
var ie = (document.all && !window.opera)?1:0;
if(!ie)
{
var e=document.captureEvents(Event.KEYDOWN)
}
window.onload=function()
{
if(!ie)
{
document.onkeydown=function(e)
{
move(e);
}
}
else
{
document.onkeydown=function()
{
move();
}
}
}
function move(e)
{
if(ie)
{
ek = window.event.keyCode;
}
else
{
var event=e;
var ek = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
}
if (ek==37) document.getElementById('DIV1').style.left=(document.getElementById('DIV1').style.left.replace('px', '')*1)-5;
if (ek==39) document.getElementById('DIV1').style.left=(document.getElementById('DIV1').style.left.replace('px', '')*1)+5;
if (ek==38) document.getElementById('DIV1').style.top=(document.getElementById('DIV1').style.top.replace('px','' )*1)-5;
if (ek==40) document.getElementById('DIV1').style.top=(document.getElementById('DIV1').style.top.replace('px','' )*1)+5;
}

</SCRIPT>
</HEAD>
<BODY>
<DIV ID="DIV1" style="position:absolute;top:100;left:100;height:20;width:20;background-color:#000000;"></DIV>
</BODY>
</HTML>


Basscyst

Pythondev
11-01-2006, 01:19 PM
Works perfect.

Thanks :D



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum