1

I've got a problem with a keypress event. I have a function that returns true or false on a keypress like this: (simplified a bit)

onkeydown (keycode == 88) xKey = true;
onkeyup    (keycode == 88) xKey = false;

if (xKey == true && bombs > 0)

    {
          this.bomb;
          bomb -= 1;
    }

Now, when you press the key, it decrements the variable to long, minimal 2 counts which doesn't add to the gameplay of course, I'm not using jQuery which has an unbind attribute and I don't want to add jQuery either, what's the old-school way? I cant find any relevant information on this but I guess I'm not the first to encounter this problem.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

1

onKeyPress Vs. onKeyUp and onKeyDown

onkeypress is both, keydown followed by keyup.

So when you do an onkeypress it will execute the onkeypress code AND the onkeyup code no matter what.

Maybe you want to keep track by using onkeydown instead so it doesn't interfere with the onkeyup functionality.

Community
  • 1
  • 1
sksallaj
  • 3,872
  • 3
  • 37
  • 58
  • I wrote the question wrong, I changed the question already I was using onkeydown already. But the problem remains the same – PenguinAdventurer Sep 11 '12 at 19:16
  • anyway, using onkeypress gets me no result at all – PenguinAdventurer Sep 11 '12 at 19:27
  • it's pretty hard to figure out what you want to do, I'm assuming you press the button, and hold it so while it's being held, the value is true. Then when you release it it's false? Can you post a jsfiddle of what you have? – sksallaj Sep 11 '12 at 19:49
  • here the whole project so far, this snippet is in index.html and the action is in Player.js – PenguinAdventurer Sep 11 '12 at 20:39
  • I want the button to return true just 1 time and then jump to keyup, I believe jQuery does this with unbind but I dont want to add jQuery to the code for just one function. – PenguinAdventurer Sep 11 '12 at 20:43
  • FIXED IT ! Wasted my evening, it was so simple and I've done it already before, just overlooked it completly: if (xKey == true && bomb > 0) { xKey = 0; bombs -= 1; this.bomb; } Sorry for wasting your time, maybe this helps someone else... GuuuudNight && thanxx 4 your replies. – PenguinAdventurer Sep 11 '12 at 20:53
0

keypress is fired repeatedly as long as the key is down. you can use keydown or keyup, or augment a throttle through an interval or timeout to only queue the request at the last keypress event

Omri
  • 278
  • 2
  • 9
  • Thanx, I have a fire button and a bomb wich works but I want to make a third button that has a charge function or similar but I dont have an idea for it yet. Also everything has to be very low on processing cuz its browser stuff, maybe I'll just start fiddling around until a gameplay element presents itself ;) as long as were having fun right !? – PenguinAdventurer Sep 12 '12 at 18:25