views:

305

answers:

1

I want to open a jQuery UI dialog when a user presses enter or space on a given element. It appears that the enter/space keys are being processed by the dialog, however, causing the default element (the cancel button) to be pressed. The dialog is closed almost as soon as it opens.

Here is a simplified demonstration:

<script type="text/javascript">
    function Go() {
        $("#dialog").text("Are you sure?").dialog({
            modal: true,
            buttons: {
                Cancel: function() {
                    $("#dialog").dialog("destroy");
                },
                OK: function() {
                    $("#dialog").dialog("destroy");
                }
            }
        });  // end .dialog
    }
</script>

<input type="button" value="Test" onkeydown="Go()" />
<div title="Dialog" style="display: none;" id="dialog"></div>

If the button is given focus and then the user presses space the dialog opens and then immediately closes. If the user presses enter, the dialog closes so quickly it doesn't even flash (at least that was my experience with Firefox 3.5.3)

How do I prevent the dialog from processing the key from the onkeydown event which caused the dialog to open?

+1  A: 

Try onkeyup if there is one. If it works, I'll give you the explanation(Busy).

Edit Explantion: It's mainly because the onkeydown event does not get called once, it gets called continually while it's pressed down, and since computers opperate so fast(1 second is eternity to them) it get's called many times during one push down. The solution is not to call it when it's pushed down, but call it on the up part(when you let go).

Happens all the time in electronics with switches and logic gates etc. I forgot the technical terms.

UK-AL
onkeyup does not automatically close the dialog. Awaiting your explanation anxiously :)
Joel Harris
It's mainly because onkeydown does not get called once, it gets called continusally while it's pressed down, and since computers opperate so fast it get's called many times during one push down. The solution call not when it's pushed down, but call it on the up part(when you let go).Happens all the time in electronics with switches etc. I forgot the technical terms.
UK-AL
The effect is called 'bounce', when related to switches
belugabob