Answer the question
In order to leave comments, you need to log in
Why doesn't addEventListener fire on keypress?
//game.js
function init() {
var moveLeft = false;
var moveRight = false;
var player = document.getElementById("player");
addEventListener("keydown", function(event){
if(event.keycode == 37)
moveLeft = true;
if(event.keycode == 39)
moveRight == true;
});
addEventListener("keyup", function(event){
if(event.keycode == 37)
moveLeft = false;
if(event.keycode == 39)
moveRight == false;
});
if(moveLeft)
alert("l");
if(moveRight)
alert("r");
}
<body onload="init();">
<div class="mainframe">
<div id="player"></div>
<input type="button" id="add" value="add">
</div>
<script src="js/game.js"></script>
</body>
Answer the question
In order to leave comments, you need to log in
First, what are you hanging the event on? to the window object?
Secondly, at the time of this code execution:
if(moveLeft)
alert("l");
if(moveRight)
alert("r");
}
events have not yet occurred, respectively, both if will be rejected
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question