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?
-
1there's no problem with the code, as you can see here: jsfiddle.net/44nqsepqNitsan Baleli– Nitsan Baleli2016年05月22日 12:29:59 +00:00Commented May 22, 2016 at 12:29
2 Answers 2
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)">
Comments
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)">