locked
delay in recognizing enter key with onkeypress RRS feed

  • Question

  • I am writing a calculator app, started with button clicks on screen and averything works great.  Now I am adding code for keypress events so you can use the keyboard.  Everthing works great, all keyboard keys work except for the enter key.  The enter key will only work after you click on an onscreen button, but all other keys work as soon as program starts.  So I can press the 5 key, then + key, then 2 key, then enter key, nothing happens.  But then I can click on the = button on screen the 7 is displayed.  After that I can then use the enter key at any time.  Here is my java script, I even tried just running the function for equals button on load just to see if it was changing soomething else I could see in the code, same results.

     

    // For an introduction to the Blank template, see the following documentation:
    // http://go.microsoft.com/fwlink/?LinkId=232509
    (function () {
        "use strict";
    
        WinJS.Binding.optimizeBindingReferences = true;
    
        var app = WinJS.Application;
        var activation = Windows.ApplicationModel.Activation;
    
        var currentNumber = "";
        var currentOperator = "";
        var previousNumber = "";
    
        app.onactivated = function (args) {
            if (args.detail.kind === activation.ActivationKind.launch) {
                if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                    // TODO: This application has been newly launched. Initialize
                    // your application here.
                 //   equalsButtonClickHandler();
                } else {
                    // TODO: This application has been reactivated from suspension.
                    // Restore application state here.
                }
                args.setPromise(WinJS.UI.processAll().then(function completed(){
    
                    // Retrieve the buttons
                    var oneButton = document.getElementById("oneButton");
                    oneButton.addEventListener("click", function () { var value = "1"; numberButtonClickHandler(value); });
                    var twoButton = document.getElementById("twoButton");
                    twoButton.addEventListener("click", function () { var value = "2"; numberButtonClickHandler(value); });
                    var threeButton = document.getElementById("threeButton");
                    threeButton.addEventListener("click", function () { var value = "3"; numberButtonClickHandler(value); });
                    var fourButton = document.getElementById("fourButton");
                    fourButton.addEventListener("click", function () { var value = "4"; numberButtonClickHandler(value); });
                    var fiveButton = document.getElementById("fiveButton");
                    fiveButton.addEventListener("click", function () { var value = "5"; numberButtonClickHandler(value); });
                    var sixButton = document.getElementById("sixButton");
                    sixButton.addEventListener("click", function () { var value = "6"; numberButtonClickHandler(value); });
                    var sevenButton = document.getElementById("sevenButton");
                    sevenButton.addEventListener("click", function () { var value = "7"; numberButtonClickHandler(value); });
                    var eightButton = document.getElementById("eightButton");
                    eightButton.addEventListener("click", function () { var value = "8"; numberButtonClickHandler(value); });
                    var nineButton = document.getElementById("nineButton");
                    nineButton.addEventListener("click", function () { var value = "9"; numberButtonClickHandler(value); });
                    var zeroButton = document.getElementById("zeroButton");
                    zeroButton.addEventListener("click", function () { var value = "0"; numberButtonClickHandler(value); });
                    var plusButton = document.getElementById("plusButton");
                    plusButton.addEventListener("click", function () { var value = "+"; operatorButtonClickHandler(value); });
                    var subtractButton = document.getElementById("subtractButton");
                    subtractButton.addEventListener("click", function () { var value = "-"; operatorButtonClickHandler(value); });
                    var equalsButton = document.getElementById("equalsButton");
                    equalsButton.addEventListener("click", equalsButtonClickHandler, false);
                    var cButton = document.getElementById("cButton");
                    cButton.addEventListener("click", cButtonClickHandler, false);
                    var ceButton = document.getElementById("ceButton");
                    ceButton.addEventListener("click", ceButtonClickHandler, false);
                    var tipButton = document.getElementById("tipButton");
                    tipButton.addEventListener("click", tipButtonClickHandler, false);
                    var multiplyButton = document.getElementById("multiplyButton");
                    multiplyButton.addEventListener("click", function () { var value = "*"; operatorButtonClickHandler(value); });
                    var divideButton = document.getElementById("divideButton");
                    divideButton.addEventListener("click", function () { var value = "/"; operatorButtonClickHandler(value); });
                    var decimalButton = document.getElementById("decimalButton");
                    decimalButton.addEventListener("click", decimalButtonClickHandler, false);
                    var squareButton = document.getElementById("squareButton");
                    squareButton.addEventListener("click", squareButtonClickHandler, false);
    
                   // equalsButtonClickHandler();
    
                    document.onkeypress = function (e) {
                        var keyPressed;
                          if (typeof event !== 'undefined') {
                              keyPressed = event.keyCode;
          
                          } else if (e) {
                            keyPressed = e.which;
                          }
                        //displayResult(keyPressed);
                          if (keyPressed == "13") {
                              equalsButtonClickHandler();
                              keyPressed = "";
                          } else {
                              keyPressed = String.fromCharCode(keyPressed);
                             // displayResult(keyPressed);
                              if (parseFloat(keyPressed) >= 0 && parseFloat(keyPressed) < 10) {
                                  numberButtonClickHandler(keyPressed);
                                  keyPressed = "";
                              } else if (keyPressed == "-" || keyPressed == "+" || keyPressed == "*" || keyPressed == "/") {
                                  operatorButtonClickHandler(keyPressed);
                                  keyPressed = "";
                              }
                          }
                        return false;
                    };
    
    
                }));
            }
        };
    
        app.oncheckpoint = function (args) {
            // TODO: This application is about to be suspended. Save any state
            // that needs to persist across suspensions here. You might use the
            // WinJS.Application.sessionState object, which is automatically
            // saved and restored across suspension. If you need to complete an
            // asynchronous operation before your application is suspended, call
            // args.setPromise().
        };
    
        
        function numberButtonClickHandler(e) {
            currentNumber = currentNumber + e;
            displayResult(currentNumber);
        }
    
        function operatorButtonClickHandler(e) {
            if (currentNumber == "") {
                currentOperator = e;
            } else {
                previousNumber = currentNumber;
                currentNumber = "";
                currentOperator = e;
            }
        }
    
        function decimalButtonClickHandler(eventInfo) {
            currentNumber = currentNumber + ".";
            displayResult(currentNumber);
        }
    
        function equalsButtonClickHandler(eventInfo) {
    
            if (currentNumber != "" && previousNumber != "") {
                if (currentOperator == "+") {
                    currentNumber = parseFloat(currentNumber) + parseFloat(previousNumber);
                } else if (currentOperator == "-") {
                    currentNumber = parseFloat(previousNumber) - parseFloat(currentNumber);
                } else if (currentOperator == "*") {
                    currentNumber = parseFloat(previousNumber) * parseFloat(currentNumber);
                } else if (currentOperator == "/") {
                    if (currentNumber != "" && currentNumber !== "0") {
                        currentNumber = parseFloat(previousNumber) / parseFloat(currentNumber);
                    } else {
                        var err = "Err";
                        displayResult(err);
                    }
    
                        
                }
                displayResult(currentNumber);
                previousNumber = currentNumber;
                currentNumber = "";
            }
        }
        function cButtonClickHandler(eventInfo) {
            currentNumber = "";
            previousNumber = "";
            currentOperator = "";
            displayResult(currentNumber);
    
        }
        function ceButtonClickHandler(eventInfo) {
            currentNumber = "";
            displayResult(currentNumber);
        }
        function tipButtonClickHandler(eventInfo) {
            if (currentNumber == "") {
                currentNumber = previousNumber;
            }
            currentNumber = parseFloat(currentNumber) * 1.2;
            currentNumber = currentNumber.toFixed(2);
            displayResult(currentNumber);
            currentNumber = "";
            previousNumber = "";
        }
        function displayResult(e) {
            var displayLabel = document.getElementById("displayLabel");
            displayLabel.innerText = e;
        }
        function squareButtonClickHandler(eventInfo) {
            if (currentNumber == "") {
                currentNumber = previousNumber;
            }
            currentNumber = Math.sqrt(parseFloat(currentNumber));
            displayResult(currentNumber);
            currentNumber = "";
        }
             
     /*       // event.type must be keypress 
        function keyDown(event) { 
            if (event.which == null) { 
                return String.fromCharCode(event.keyCode) // IE 
                } else if (event.which!=0 && event.charCode!=0) { 
                    return String.fromCharCode(event.which)   // the rest 
                    } else { 
                    return null // special key 
                    } 
            } 
    */
    
        
    
        app.start();
    })();
    

     My code probably isnt perfect this is my first program I'm writing
    • Edited by roconnor Sunday, December 16, 2012 10:27 PM
    Sunday, December 16, 2012 10:25 PM

Answers

  • I can't seem to find an error on the code, you could try a could of things:

    • keyPress==13 instead of keyPress=="13"
    • keyPressed = e.keyCode; instead of keyPressed = e.which;
    • Using OnKeyDown. I always use the OnKeyDown event for detecting the ENTER key, it has yielded better results than OnKeyPress.
    • Marked as answer by roconnor Monday, December 17, 2012 2:40 PM
    Monday, December 17, 2012 2:05 PM

All replies

  • I can't seem to find an error on the code, you could try a could of things:

    • keyPress==13 instead of keyPress=="13"
    • keyPressed = e.keyCode; instead of keyPressed = e.which;
    • Using OnKeyDown. I always use the OnKeyDown event for detecting the ENTER key, it has yielded better results than OnKeyPress.
    • Marked as answer by roconnor Monday, December 17, 2012 2:40 PM
    Monday, December 17, 2012 2:05 PM
  • thanks I added a keydown function that only looked for the enter key and it worked perfectly.  Thanks again
    Monday, December 17, 2012 2:42 PM