jQueryUI Modal Dialog
jQueryUI Modal Dialog doesn't block RETURN or ESCAPE keyup event
by redoak2000
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-darkness/jquery-ui.css">
<div id="container" tabindex="1" class="ui-widget ui-widget-content ui-corner-all">
<!-- tabindex attribute is needed so #container can take focus -->
<button id="clickme">Click Me!</button>
<input id="info" class="ui-button ui-corner-all"/>
</div>
<!--
Type stuff and you'll see the keydown and keyup events in the info box.
Press "Click Me!" to open a modal dialog box. further keyboard input is ignored
because the dialog has disabled everything beneath it.
Press "Ok" to dismiss the dialog and #container regains keyboard focus, but...
- if you use RETURN to press "Ok" then a stray "keyup" event hits #container
- this does not happen if you press "Ok" with the spavebar instead
- you also get a stray "keyup" event if you press ESCAPE to dismiss the dialog
Also, is you press "Click Me!" using RETURN then the dialog opens on the "keydown"
event while if you press it using the spacebar the dialog opens on "keyup".
Why does RETURN trigger a button "click" event on "keydown" and not "keyup"?
-->
CSS
#container {
display: table-cell;
vertical-align: middle;
text-align: center;
padding: 20px;
}
JavaScript
$("#clickme").button()
.click(function(e){ $.alert("You clicked me!"); $("#info").val("") });
$("#container").focus()
.on("keydown keyup", function(e){
$("#info").val("type="+e.type+" which="+e.which);
});
$.extend({
// taken from https://coding.abel.nu/2012/01/jquery-ui-replacement-for-alert/
alert: function (message, title) {
$("<div/>").dialog({
open: function() { $(".ui-dialog-titlebar-close", $(this).parent()).hide(); },
buttons: { "Ok": function() { $(this).dialog("close"); } },
close: function() { $(this).dialog("destroy"); },
resizable: false,
title: !title ? "Warning" : title,
modal: true,
}).html(message);
}
});