skip to Main Content

all modals can close using press esc key by human.
I want to do this through javascript code without actual human intervention
I run the following code through the browser console, but it does not work at all
Can anyone solve my problem?

document.dispatchEvent(new KeyboardEvent('keydown', {'key': 'Escape'}));

To test, you can go to the link and test

2

Answers


  1. Perhaps this will work.

    <!-- HTML code for the Bootstrap modal -->
    <div class="modal" id="myModal">
      <div class="modal-dialog">
        <div class="modal-content">
          <!-- Modal header, body, and footer content here -->
        </div>
      </div>
    </div>
    
    <!-- JavaScript code to listen for the escape key press -->
    <script>
    document.addEventListener('keydown', function(event) {
      if (event.key === "Escape") {
        var modal = document.getElementById("myModal");
        if ($(modal).data('bs.modal')._isShown) {
          $(modal).modal('hide');
        }
      }
    });
    </script>
    
    
    Login or Signup to reply.
  2. This worked for me

    document.getElementById('myModal').dispatchEvent(new KeyboardEvent("keydown",{
            keyCode: 27,
            which: 27,
            key: 'Escape',
            code: 'Escape'
         }));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search