简体   繁体   中英

Can someone explain how to use an event listener in the most simple of terms?

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM