How to send user to home page if escape key clicked on JQuery modal dialog box

Robertcode :

Is there a way to jump to a web home page when the escape key is pressed on a modal dialog box? Below is the modal dialog box I am using:

        <script>
            $(function () {
                $("#dialog-login-message").dialog({
                    modal: true,
                    buttons: {
                        Ok: function () {
                            document.location.href = "/";
                            $(this).dialog("close");
                        }
                    }
                });
            });
        </script>

        <div id="dialog-login-message" title="Login Required">
            <p>
                <span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
                You are not logged into this website. You need to be logged into this website to use the demo.;
            </p>
        </div>

If a user is not authenticated this dialog appears. If they press OK it takes them to the home page. But if they press the escape key the dialog is passed by and the view continues to become available. I would like to send the user back to the home page but I'm not sure how from here. Thanks in advance.

Jerdine Sabio :

You could simply attach a keyup/keydown event and get the clicked button;

$(document).keyup(function(e) {
  if (e.keyCode === 27){ // 27 is esc keycode
     $(this).dialog("close");
     document.location.href = "/";                
  }
});

BUT, this event will be bound on the page, hence pressing esc at any time will redirect you to the homepage.

What you want to do is add a var modalState that will determine if that dialog is active.

<script>
   var modalState = 0; // declare it outside, 0 means unopened

   $(function () {
       modalState = 1; // change it to active

      $("#dialog-login-message").dialog({
         modal: true,
         buttons: {
            Ok: function () {
               document.location.href = "/";
               $(this).dialog("close");
            }
         }
      });
   });

   $(document).keyup(function(e) {
      if (e.keyCode === 27){ // 27 is esc keycode
         if(modalState == 1){ // check if dialog is active
            $(this).dialog("close");
            document.location.href = "/"; 
         }              
      }
   });
</script>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=302048&siteId=1