1

I have a html5 and javascript game as follows:

<html>
<head>
 <title>Garrid Punching</title>
 <style>
 canvas {
 border: 1px solid black;
 background-color: black
 }
 </style>
 <script>
function answer(e) {
 if (e.keyCode === 13) { //enter key pressed
 alert("it worked")
 }
 }
</script>
</head>
<body onkeypress="return answer(event)">
<canvas width="1080" height="480" id="myCanvas"></canvas>
</body>
</html>

What is expected to happen is that when the enter key is pressed, Javascript receives the event and then interprets the keycode to be equal to 13, causing it to send an alert that says "It worked".

However, when I press enter nothing happens, and it instead returns the problem "function 'answer' not defined" in the debugger.

Why would this be so?

asked May 22, 2016 at 12:27
1
  • 1
    there's no problem with the code, as you can see here: jsfiddle.net/44nqsepq Commented May 22, 2016 at 12:29

2 Answers 2

3

I tried this in Chrome and it works absolutely fine. What browser are you using to test this ?

Try removing the return keyword and call the function right away.

<body onkeypress="answer(event)">
answered May 22, 2016 at 12:35
Sign up to request clarification or add additional context in comments.

Comments

0

Your code works just fine, check if your browser is automatically blocking JavaScript alerts.

BTW, you should change

<body onkeypress="return answer(event)">

To

<body onkeypress="answer(event)">
answered May 22, 2016 at 12:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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