Search code examples
javascriptjqueryevent-handlingalertkeyevent

Javascript: how to prevent keypress used to dismiss alert from triggering key event handler


I am creating a web-based experiment using Javascript / JQuery which requires users to give responses by pressing certain keys, but not others. If they press the wrong key, they are supposed to get an alert popup telling them that they pressed the wrong keys. The experiment should stop waiting for the next keypress while the alert is displayed, but go back to waiting once the alert is dismissed.

The problem I'm having is that if the alert is dismissed by pressing the ENTER key, it seems to be registered by the key event handler, thus triggering another alert (because ENTER isn't one of the permitted keys), even though I thought I'd written it in such a way that the key event handler shouldn't be called until after the alert is dismissed. My question is, how to ensure that an ENTER keypress used to dismiss the alert will not be received by the subsequently called event handler?

Here's some code:

function waitForKeypress( permittedKeys, callbackFn ) {
    returnFn = function(e) {
        $(document).unbind('keyup',returnFn);
        if ( permittedKeys.indexOf( e.which )!=-1 ) {
            callbackFn( { "success": true, "value": e.which } );
        } else {
            callbackFn( { "success": false } );
        }
    }
    $(document).keyup( returnFn );
}

var callback = function(data) {
    if ( data.success ) {
        goDoOtherStuff();
    } else {
        alert( "error message" );
        waitForKeyPress( permittedKeys, callback );
    }
}

waitForKeyPress( permittedKeys, callback );

I should explain that the reason I THOUGHT that an ENTER keypress used to dismiss the alert would not be received by the event handler in waitForKeyPress is because (I thought) Javascript should halt execution as long as the alert is displayed, so that the waitForKeyPress call inside the callback function should not go off until the alert has been dismissed, which is to say, after the ENTER key has been released.

(My actual waitForKeyPress is more complicated than the above - it waits for PAIRS of key presses, with only certain pairs permitted, which is the reason why I needed to make it a separate function in the first place. I don't think the stuff I removed is related to my problem, though.)

EDIT: some people suggested this might have to do with the event handler not being unbound properly. I'm sure this isn't the issue. Here's a much more concise example, where the event handler isn't even bound at all until after the alert, but the same issue arises:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
alert( "Hello world" );
$(document).keyup( function() { alert( "Goodbye cruel world." ) } );
</script>
</html>

Pressing ENTER to dismiss Hello World will immediately call up Goodbye cruel world.


Solution

  • unbind keyUp before showing the alert

    edit #1

    I tried the example code in your edit on Safari 6 OS X 10.7.

    You're right.

    This happens because standard buttons, like tke "Ok" of the alert dialog, that have the key equivalent "Return", are pressed (I mean the button) when a Return keydown occurr. In other words the dialog is dismissed as the user press return and doesn't wait for Return to be released.

    So the user press "Return", the dialog is dismissed, keyup is binded, the user releases "Return", the event is fired.

    You may work around this behaviour in different ways.

    The easier one (if it fits your needs) is binding keydown instead of keyup

    alert( "Hello world" );
    $(document).keydown( function() { alert( "Goodbye cruel world." ) } );
    

    Otherwise you may check what key is pressed and ignore "Return".

    Keep in mind that keydown is triggered also by pressing CMD (for example if the user wants to close the window with CMD-W), arrow keys (that normally allow user to scroll the window if content is bigger that the viewport), etc.

    So either if you stck with keyup or switch to keydown some sort of filtering would be appropriate.

    Hope this helps