How to Close the SharePoint Modal Dialogs with Escape (ESC) Key Press

Sathish Nadarajan
SharePoint MVP
Published On :   06 Dec 2015
Visit Count
Today :  2    Total :   5264
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

Sharegate: Kick-Ass Tool
Think Your SharePoint & Office 365 Are Secure ? Find Out Now!

In one of our recent application, there are many Screens, which we are supposed to open them as Modal dialogs.

To Open the Modal Dialog, I was using the below method.

 function OpenDocTopicPopup(bookcaseTopic) {
     var options = {
         url: '/pages/MyPage.aspx?Topic=' + MyTopicVariable + '&TermID=' + _spFriendlyUrlPageContextInfo.termId,
         title: ‘TEst’,
         allowMaximize: false,
         showClose: true,
         width: 1200,
         height: 500,
         dialogReturnValueCallback: Function.createDelegate(null, function (result, returnValue) {
             if (result == SP.UI.DialogResult.OK) {
 function OpenDocTopicPage(returnValue) {
     window.location.href = window.location.href + "/" + returnValue;

After opening the Dialog, the Dialog has a Close Button. But it is not user friendly. Basically, the user will be tempted to press the Escape key and expect the Modal to be closed. To do that, we need to inject the below piece of code in the Master Page.

 // Close modal dialog by pressing ESC-Key
 $(document).keydown(function (e) {
     e = window.event || e;
     // Check if ESC-Key is pressed
     if (e.keyCode == 27) {
         // Check if a dialog was recently opened
         var dialog = SP.UI.ModalDialog.get_childDialog();
         if (dialog != null) {
             // Try to close the dialog
                 "Closed by ESC");

Though this seems to be a small, this will definitely safe some development time.

Happy Coding,

Sathish Nadarajan.

SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.

Protect Your SharePoint