javascript - Can someone explain how to use an event listener in the most simple of terms? -
i beginner coder in high school programming class, trying edit html/javascript game found online , update function called acceleration:
function accelerate(n) { mygamepiece.gravity = n; }
with keypress or keydown/up event. make box accelerate or down whether spacebar pressed. issue event listener examples can find use buttons, , game works using acceleration button:
<button onclick="" onkeydown="accelerate(-.5)" onkeyup="accelerate(.5)">start game</button>
the issue want window / document (i don't know is) detect if user inputting spacebar key , update acceleration function accordingly. appreciate willing give, thank :d
you can (and should) use addeventlistener
. it's better way of setting event handlers since isn't mixed in html, can done on dynamic elements , allows multiple handlers single event.
document.addeventlistener('keydown', function(e) { // prevent space causing page scroll e.preventdefault(); // nice tool finding key codes: http://keycode.info/ var ispressingspace = (e.keycode === 32); var ispressinga = (e.keycode === 65); // can use a, if want if (ispressingspace || ispressinga) { document.queryselector('span').innertext = 'accelerating'; } }); document.addeventlistener('keyup', function() { document.queryselector('span').innertext = 'decelerating'; });
<span>decelerating</span>
Comments
Post a Comment