0

Before the button ("play") is clicked, the program handles keydown but after clicking the button which draws a table, thereafter keydown messages are not handled. I want this to work in IE or Firefox.

<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>
1
  • What exactly do you want to work? Commented Jul 31, 2010 at 17:35

2 Answers 2

1

You may want to read this article: http://java-programming.suite101.com/article.cfm/javascript_documentwrite_tutorial

The document.write command must be carried out during the loading of the page. So, if it is attached to any event that executes after the page has loaded, then the whole page will be replaced with the contents of the document.write command.

Rather than using document.write, you might want to instead use getElementById and then put your HTML in the innerHTML property of the element that you want the text to be in.

That may require adding a new div to hold the new text.

Sign up to request clarification or add additional context in comments.

1 Comment

This. Also, use something like document.getElementById('mine') instead of just using mine directly (which should only work in quirks mode).
0

Since the answer would be rather long just => look here

in short document.write is just not the right way to go. use smth different like document.createElement or go for a nice'n'easy javascript framework like jquery.

there you could just

var html = "";
html += "<table id='mine' align='center' height='500px' cellSpacing='0' cellPadding='0' width='500px' border='4' >";
html += ...
$(html).appendTo("body");

hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.