jQuery UI dialog button focus

davidsleeps picture davidsleeps · Nov 25, 2009 · Viewed 69.5k times · Source

When a jQuery UI dialog opens, it selects one of the buttons and highlights it or sets focus to it etc... How can I stop this behaviour so that none of the buttons are highlighted when the dialog opens?

EDIT: I tried the following in the dialog options, which didn't remove focus from the buttons:

...
open:function(event, ui) { $("myunimportantdiv").focus(); },
...

NOTE: As a temporary workaround I modified the CSS for .ui-state-focus but this isn't ideal...

Answer

Ed I picture Ed I · Feb 3, 2010

Use the blur method. You can try this sample.

<html>
    <head>
        <title>No Focus on jQuery Dialog</title>
        <link type="text/css" rel="stylesheet" href="ui.all.css" />
        <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
        <script type="text/javascript" src="ui.core.js"></script>
        <script type="text/javascript" src="ui.dialog.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                // Dialog to confirm or cancel
                // Focuses on confirm by default.
                $('#noFocusDialog').dialog({
                    autoOpen: false,
                    buttons: {
                        Confirm: function() {
                            $(this).dialog('close');
                        },
                        Cancel: function() {
                            $(this).dialog('close');
                        }
                    }
                });

                // Trigger to open the dialog
                $('#openNoFocusDialog').click(function() {
                    $('#noFocusDialog').dialog('open');

                    // Remove focus on all buttons within the
                    // div with class ui-dialog
                    $('.ui-dialog :button').blur();
                });
            });
        </script>
    </head>
    <body>
        <a id="openNoFocusDialog" href="#">Open Dialog</a>
        <div id="noFocusDialog">
            <p>Confirm that no elements have focus</p>
        </div>
    </body>
</html>