0

I wrote a function which should check if one particular button is being pressed. However, it seems to always return false. This is the function:

function keyPressed(ev) { var r = false; document.onkeypress = function(e) { if (ev == e.which || ev == e.keyCode) { r = true; } } return r; } 

And this is how you'd call it:

if (keyPressed(119)) { // do something } 

Checking with alert, they seem to be the same number when I press "W", but the function just always returns false. Are they different type?

1 Answer 1

1

document.onkeypress will be executed each time you press a key. But keyPressed will be executed only when you call it. So, except if you launch keyPressed(touch) at the same time you're pushing touch, it will always return false.

What you did there is: when I call keyPressed(), bind a function to document.onkeypress. Then return r, which has not been modified by the binding.

I suggest you try to put a switch-like structure with callbacks in a big document.onkeypress function.

Bonus: e.which is deprecated, use e.key if possible.

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

3 Comments

I'm actually using the keyPressed -function in a loop which is updated every second. I updated the function to compare "ev" and "e.key", and now it works, kind of. Is there any way to return true or false there?
What you described sounds like you'll be creating redundant bindings to document every second. You may be headed down the wrong track.
I second @gfullam, that's a bad practice. You should bind a function to document.onkeypress only once, and then update it depending of what you want. Concerning your true/false question, r is unecessary: just replace r = true by return true. And return r by return false.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.