0

I am trying to get a count from 100 to count up/down by 1 when a keyboard button is pressed. I am currently using the keys 8 and 2 on the keypad which correspond to 104 and 98 ascii numbers.

At the moment the code I am using counts down but I cannot get it to count up on 104 key press.

What am I missing.

var keyY = 100;

document.addEventListener('keydown', function(event){
  var keyPressed = event.keyCode;
  switch(keyPressed){
    case 104:
      keyY = keyY + 1;
    case 98:
      keyY = keyY - 1;
  }
  console.log('key pressed: ' + keyPressed);
  console.log('keyX = ' + keyY);
});
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
      <script src="index.js"></script>
  </body>
</html>

1

1 Answer 1

5

You're missing the break, which is very important.

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

From here

var keyY = 100;

document.addEventListener('keydown', function(event){
  var keyPressed = event.keyCode;
  switch(keyPressed){
    case 104:
      keyY++;
    break;
    case 98:
      keyY--;
    break;
  }
  console.log('key pressed: ' + keyPressed);
  console.log('keyX = ' + keyY);
});

EDIT: use keyY++; instead of keyY = keyY + 1; & keyY--; instead of keyY = keyY - 1;

Sign up to request clarification or add additional context in comments.

3 Comments

Just a little extra I would like to add, but it's totally not necessary, is using keyY++ or keyY--
Thanks, i was using Y++ and Y-- and have used Switch a few times, can't believe I missed the break, been annoying me all morning, such a silly mistake. thank you for getting me back on track
@GiovaniVercauteren I added it to the answer. Thank you for the improvement.Steve8428 No problem. Sometimes that happens to me too ;)

Your Answer

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