1

I am a beginner coder in my high school programming class, I am currently trying to edit a HTML/Javascript game I found online and I would like to update a function called acceleration:

function accelerate(n) {
    myGamePiece.gravity = n;
}

with a keypress or keydown/up event. What it would do is make a box accelerate up or down whether the spacebar is pressed. The issue is the only good event listener examples I can find use buttons, and the game currently works using an acceleration button:

 <button onClick="" onkeydown="accelerate(-.5)" onkeyup="accelerate(.5)">Start Game</button>

The issue is that I want the window / document (I don't know which it is) to detect if the user is inputting the spacebar key and to update the acceleration function accordingly. I would very much appreciate any help anyone would be willing to give, thank you :D

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
  • 1
    You can try this: `function accelerate(n) { if (event.keyCode == 32) myGamePiece.gravity = n; }` – vbguyny Nov 17 '16 at 19:26
  • 1
    The event listeners you've used here, like `onclick`, `onkeydown`, etc. can be used an any tag. You could put it on `` if you wanted. In general though, it's much better to [bind your event listeners from the JS rather than the HTML](http://stackoverflow.com/q/6941483/5743988). – 4castle Nov 17 '16 at 19:27

1 Answers1

5

You can (and should) use addEventListener. It's a better way of setting up event handlers since it isn't mixed in with your HTML, can be done on dynamic elements and allows multiple handlers for a single event.

document.addEventListener('keydown', function(e) {
  // Prevent space from causing the page to scroll
  e.preventDefault();
  
  // A nice tool for finding key codes: http://keycode.info/
  var isPressingSpace = (e.keyCode === 32);
  var isPressingA = (e.keyCode === 65); // Can also use A, if you want
  if (isPressingSpace || isPressingA) {
    document.querySelector('span').innerText = 'Accelerating';
  }
});

document.addEventListener('keyup', function() {
  document.querySelector('span').innerText = 'Decelerating';
});
<span>Decelerating</span>
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • Thank you very much for the assistance, however I'm confused about the output of the if statement, the document.querySelector('span').innerText = 'Accelerating'; is what confuses me. Currently in order to make my box accelerate, I need to input a value into the acceleration function (.5 & -.5) in order to move the box. I would like to know how to use the if statement to update the input for this function, and I would be very grateful if you would be willing to help me. Thank you very much :) – Beau_Henry_ Nov 18 '16 at 18:14
  • @Beau_Henry_ All I'm doing is assigning some text to an element. In your case, just call your function. Replace the `...innerText = 'Accelerating';` with `accelerate(0.5)`. – Mike Cluck Nov 21 '16 at 16:39