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

Sathish Nadarajan
Solution Architect
December 6, 2015
Rate this article
[Total: 0    Average: 0/5]

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.

Author Info

Sathish Nadarajan
Solution Architect
Rate this article
[Total: 0    Average: 0/5]
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 13+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business more

Leave a comment