A
A
Alexey Esin2016-01-26 17:22:12
JavaScript
Alexey Esin, 2016-01-26 17:22:12

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");
}

The code is included after loading the body
<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>

What's wrong with the code?
I saw somewhere that if you enter a function with brackets () into the arguments of addEventListener , then this will cause it to be immediately executed.
But does this rule apply to this kind of record ( function(event){}) ?
And is this the cause of the error?
There is nothing in the console.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2016-01-26
@royal-gaben

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 question

Ask a Question

731 491 924 answers to any question