1

I need help with a keyboard event. So what i want to happen is when you press the w and the 2 key i want to add one to water instead of one to wood (as an alternative when pressing the w key without the 2 it will add one to wood. But i only want the wood and the water to update once instead of adding one when you hold down the key. heres some code

var wood = 0;
var water = 0;
var woodOut = document.getElementById('wood');
var waterOut = document.getElementById('water');

window.addEventListener("keydown", key);

function key() {
  var x = event.which || event.keyCode;
  if(x == 87){
    wood = wood + 1;
    woodOut.innerHTML = wood;
  }
  if(x == 87 && x == 50){
     water = water + 1;
     waterOut.innerHTML = water;
  }
}
<p id="wood">0</p>
<p id="water">0</p>
Liam Sperry
  • 318
  • 2
  • 9
  • 1
    your second if will never be true, try as explained [here](http://stackoverflow.com/questions/5203407/javascript-multiple-keys-pressed-at-once) – Kevin Kloet Dec 21 '16 at 12:55

3 Answers3

1

You need to keep track on previous key that was pressed (w+1 will add for wood, w+2 for water):

var wood = 0;
var water = 0;
var woodOut = document.getElementById('wood');
var waterOut = document.getElementById('water');
var previous_key;


window.addEventListener("keydown", key);

function key() {
  var x = event.which || event.keyCode;
  if(x== 49 && previous_key == 87){
    wood = wood + 1;
    woodOut.innerHTML = wood;
  }
  if (x == 50 && previous_key == 87){
     water = water + 1;
     waterOut.innerHTML = water;
  }
  previous_key = x;
}
<p id="wood">0</p>
<p id="water">0</p>
Slonski
  • 824
  • 5
  • 12
0

Actually, it's very easy if I understood what you want. You need to just create a Map object with two properties which are your keyCode and put them in false. when both W and 2 pressed then you can file what you want.

Have a look at the following code and try to just press w first and then w+2:

   var wood = 0;
var water = 0;
var woodOut = document.getElementById('wood');
var waterOut = document.getElementById('water');
var map = {87: false, 50: false,};
window.addEventListener("keydown", keyDown);
window.addEventListener("keyup", keyUp);

function keyDown(e) {
if (e.keyCode in map) {
    map[e.keyCode] = true;
    if (map[87]) {
        wood = wood + 1;
        woodOut.innerHTML = wood;
    } 
    if(map[50] && map[87]){
      water = water + 1;
      waterOut.innerHTML = water;
  }
}
 
}
function keyUp(e) {
  if (e.keyCode in map) {
    map[e.keyCode] = false;
  }
}
<p id="wood">0</p>
<p id="water">0</p>
Majid
  • 2,507
  • 2
  • 19
  • 18
0

If you want to update it only once when you hold down the key. Try this

window.addEventListener("keyup", key);
Saroj
  • 1,551
  • 2
  • 14
  • 30