views:

27

answers:

1

i want the program to handle keydown messages after the table is printed(after clicking the button).Before the button is clicked,the program handles keydown mess but after i click the button it doesn't.

<html>
<head>
<script type="text/javascript">
var matrix,xbody,ybody,dir,key;
function draw()
{
    for(var i=0;i<xbody.length;i++)
    {
        matrix[xbody[i]*50+ybody[i]].bgColor="black";
    }
alert("draw");
}
function init()
{
document.write("<table id='mine' align='center' height='500px' cellSpacing='0' cellPadding='0' width='500px' border='4' >");
    for(var i=0;i<50;i++)
    {
    document.write("<tr>");
    for( var j=0;j<50;j++)
    document.write("<td></td>");        
    document.write("</tr>");
    }
document.write("</table></div>");
matrix=mine.getElementsByTagName("td");
xbody=new Array();
ybody=new Array();
xbody[0]=ybody[0]=0;
draw();
alert("pop");
}

function keypress(e)
{
alert("aiyoooo");
if((e.keyCode==38)|| ((e.which)&&(e.which==38)))
key=0;
else if((e.keyCode==40)|| ((e.which)&&(e.which==40)))
key=1;
else if((e.keyCode==37)|| ((e.which)&&(e.which==37)))
key=2;
else if((e.keyCode==39)|| ((e.which)&&(e.which==39)))
key=3;
}   
</script>
</head>
<body onkeydown=keypress(event)>
<br/>
<input type="button" onClick="init()" value="play">
</body>
</html>
A: 

The following works in Chrome ... instead of defining the on keydown as an attribute of the body tag, just do this in your script tag.

document.onkeydown = function ()
{
    var e = event;
    alert( "keycode:" + e.keyCode );
    if((e.keyCode==38)|| ((e.which)&&(e.which==38)))
        key=0;
   // continued ...
BioBuckyBall
thanks man, it is working beautifully.in my lab they don't have chrome and i am not supposed to install it... any idea how to make it work for IE or firefox?
kannan

related questions