2

I am creating a html page which contains a question (a puzzle like situation ). The answer for the question is "Windows 7", but I want the user to get through the question only if he presses windows key followed by 7. I want to create a JavaScript function for this. I am able to capture the individual key press by getting the ASCII value of the keystroke., but when I try to do it in combination its not working. How to go about solving this? Any ideas?

2 Answers 2

5

http://jsfiddle.net/loktar/MsNPW/5/

var keys = [];

document.onkeydown = function(evt){    
   var key = evt.keyCode;
   keys[key] = true;
    if(keys[91] && keys[55]){
       console.log("win7");
    } 
}

document.onkeyup = function(evt){    
   var key = evt.keyCode;
   keys[key] = false;
}
Sign up to request clarification or add additional context in comments.

2 Comments

there's a bug that i can't seem to fix...if you answer it correctly once, the next time you answer something you'll get a 'correct' response even if it's wrong
@mrmo123 hmm could try this, jsfiddle.net/loktar/MsNPW/4 Fixed the alert was stopping the keyup from being run. Edited answer.
1

You can detect keydown and keyup events, and keep a list of keys that have been pressed. Add the key to the list on keydown, and remove them from the list on keyup. From there you can just check the list at appropriate times (e.g. at the end of the keydown event).

Remember that each keypress is it's own unique event. Multiple keys being pushed aren't naturally related, so that's why you need to create this list yourself.

I suggest you use a library like jQuery, and there may be plugins which can help. That said, the general concept I described shouldn't be too tough to implement yourself. Let me know if pseudocode would help clarify the algorithm I'm describing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.