1

Here is my code:

<html>
<head>
<title>My Game Title Goes Here!</title>
<script type="text/javascript">
function startGame(){
    document.getElementById("2").innerHTML = ('Testing!');
}
document.body.onload = keyListener(){
    document.getElementById("1").onkeypress = startGame;
}
</script>
</head>
<body>
<div class="title" name="Game Title" id="0">Game Title</div>
<div tabindex="0" class="gamecontainer" name="Game Container" id="1">
Press any key to start.
</div>
<div class="gamemonitor" name="Game Monitor" id="2">
Game Monitor:
</div>
</body>
</html>

I doesn't work like I expect it to (I'm using Google Chrome).

It only works if I run it directly, like this:

<div tabindex="0" class="gamecontainer" name="Game Container" id="1" onkeypress="document.getElementById('2').innerHTML = ('Testing!')">
Press any key to start.
</div>
<div class="gamemonitor" name="Game Monitor" id="2">
Game Monitor:
</div>

I checked over my code tons of times and i cannot find any clear mistakes like typos or anything. If that is the problem then I am sorry to have wasted your time but this is realy buggin' me.

kukac67
  • 298
  • 1
  • 3
  • 12

5 Answers5

2

Element IDs can't start with a number, it's almost definitely contributing to your issue here. Change the IDs in both the HTML and JS to begin with a letter.

Second of all, the keyListener line should probably be something like this:

window.onload = function(){
    document.getElementById("newId").onkeypress = startGame;
}
Community
  • 1
  • 1
Dunhamzzz
  • 14,682
  • 4
  • 50
  • 74
1

Change :

document.body.onload = keyListener(){
    document.getElementById("1").onkeypress = startGame;
}

To:

document.body.onload = function(){
    document.getElementById("1").onkeypress = startGame;
}

And, id shouldn't begin with a number as it's an invalid HTML.
Chrome seems to overcome this mistake, but it shouldn't be used.

And move the code to the the <body> tag or use window.onload
document.body doesn't exist above the <body>.

gdoron
  • 147,333
  • 58
  • 291
  • 367
1

document.body doesn't have an onload property. It should be window.onload instead.

window.onload = function(){
    document.getElementById("1").onkeypress = startGame;
}

DEMO: http://jsfiddle.net/9khng/

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
0

I think IDs can't start with a number.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Michi
  • 2,480
  • 3
  • 28
  • 38
  • You're right, but this isn't the issue here, he's using the same id in the second inline way. see my answer. – gdoron Jun 07 '12 at 15:26
0

Try fixing your "onkeypress" attribute. Your quotes are messed up.

onkeypress="document.getElementById('2').innerHTML = ('Testing!')"
Hacknightly
  • 5,109
  • 1
  • 26
  • 27