show modal and prevent bootstrap modal from disappearing when clicking outside or pressing escape in javascript in javascript

You can use JavaScript to show a Bootstrap modal and prevent it from disappearing when clicking outside or pressing the escape key. You can achieve this by adding an event listener to the modal and using the preventDefault() method.

Here is an example code:

<!-- Button to trigger the modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
949 chars
26 lines
index.tsx
// Get the modal element
var modal = document.getElementById('exampleModal');

// Add an event listener to the modal
modal.addEventListener('click', function (event) {
  // Prevent the default behavior
  event.preventDefault();

  // Check if the clicked element is the modal itself or a descendant of the modal
  if (event.target === modal) {
    modal.style.display = 'block'; // Show the modal
  }
});

// Add an event listener to the document
document.addEventListener('keydown', function (event) {
  // Prevent the default behavior
  event.preventDefault();

  // Check if the escape key was pressed
  if (event.key === 'Escape' || event.key === 'Esc') {
    modal.style.display = 'block'; // Show the modal
  }
});
721 chars
25 lines

In this example, we get the modal element using its ID and add an event listener to it. When the modal is clicked, we prevent the default behavior and check if the clicked element is the modal itself or a descendant of the modal. If it is, we show the modal by setting its display property to 'block'.

We also add an event listener to the document for the keydown event. When the escape key is pressed, we prevent the default behavior and show the modal in the same way as for the click event.

gistlibby LogSnag