Close SharePoint Dialog Box with the Esc Key

When we want to check or edit a SharePoint list element without navigating around different pages, we can use a dialog box. The dialog box has been available since SharePoint 2010 and is very useful as the user can quickly return to the list from which he started by closing the dialog box, eliminating the need to navigate different pages.

Users have gotten used to closing dialog boxes in browsers with the Escape key, regardless if it displays a picture, video or text.

But the SharePoint dialog box isn’t exactly user friendly – the Escape key doesn’t close the dialog box and the user must manually move the mouse cursor to the x button and click on it in order to close the dialog box.

We can solve this with a bit of simple JavaScript. First, we need to add a module to the project. This module will load the JavaScript. We then add the following code into the elements.xml file:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
    ScriptSrc="~sitecollection/Style Library/DetectKey/CloseWithEsc.js"
    Location="ScriptLink" Sequence="102" >
  </CustomAction>
  <Module Name="DetectKey" Url="Style Library">
    <File Path="DetectKey\CloseWithEsc.js" 
          Url="DetectKey/CloseWithEsc.js" />
  </Module>
</Elements>

The module adds the JavaScript (in this example called CloseWithEsc.js) into the Style Library.

The JavaScript is simple, made up of only a couple of lines of code. First, it detects that a key has been pressed. It then checks if that key was Escape. After that it detects if a dialog box is open and if so, closes it.

document.onkeypress = function(e) {
e = window.event || e;
if (e.keyCode == 27) {
    var dialog = SP.UI.ModalDialog.get_childDialog();
    if (dialog != null) {
        SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel,
            "Closed by ESC");
    }
}

After we load the project, we need to activate the function into which we added the module. Then, the JavaScript file will be added to the Style Library.

But if we would like to make the code even simpler and if we can change the master page, we can call a file with the following code directly from the master page (we must first load jQuery):

$( document ).ready(function() {
    $(document).keydown(function (e) {
        e = window.event || e;
        if (e.keyCode == 27) {
            var dialog = SP.UI.ModalDialog.get_childDialog();
            if (dialog != null) {
                SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel,
                    "Closed by ESC");
            }
        }
    });
});

With this simple solution we can slightly improve and simplify the use of SharePoint dialog boxes in list element revisions.

Leave a Reply

Your email address will not be published. Required fields are marked *