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

One way to prevent a Bootstrap modal from disappearing when clicking outside or pressing escape is to add an event listener to the modal itself, and then use preventDefault() to stop the events from propagating.

Here's an example:

index.tsx
// Get the modal element
const modal = document.getElementById('myModal');

// Add an event listener to the modal itself
modal.addEventListener('click', function(e) {
  // If the click is not on the modal-content, prevent it from propagating
  if (e.target === modal) {
    e.preventDefault();
    e.stopPropagation();
  }
});

// Add an event listener to the document itself
document.addEventListener('keydown', function(e) {
  // If escape key is pressed, prevent it from propagating
  if (e.keyCode === 27) {
    e.preventDefault();
    e.stopPropagation();
  }
});
569 chars
21 lines

In this example, we are adding an event listener to the modal itself to capture any clicks inside the modal. If the click is not on the modal-content, we prevent the event from propagating to the document, thus preventing the modal from disappearing.

We are also adding an event listener to the document itself to capture any keydown events. If the escape key is pressed, we prevent the event from propagating to the document, thus preventing the modal from disappearing.

Note that we are using stopPropagation() in addition to preventDefault() to prevent the event from reaching other event listeners on the document.

gistlibby LogSnag