How can I close or hide a Bootstrap modal using JavaScript?

Solution 1: Use jQuery’s Bootstrap modal method

Open the browser console (Chrome DevTools, Firefox Firebug, etc.) and try:


$('#myModal').modal('hide');

1. If the modal closes, your JavaScript is working.

2. If it doesn’t, check for:

  • Duplicate element IDs
  • Whether it works the first time but not subsequent times
  • Whether the JavaScript is correctly loaded after the modal

This helps debug whether the issue is client-side or server-side.

Solution 2: Pass 'hide' as an option

You can programmatically hide a modal like this:


$('#modal').modal('hide');

Bootstrap also provides events like hidden.bs.modal if you want to trigger actions after the modal is hidden.


$('#modal').on('hidden.bs.modal', function () {
    console.log('Modal is now hidden.');
});

If this doesn’t work, you can assign an ID to your modal’s close button and trigger a click:


$('#closeButton').click();

Solution 3: Directly hide modal and backdrop (last resort)

If all else fails (e.g., Bootstrap 3.4 issues), you can manually hide the modal and its backdrop:


$('#myModal').hide();
$('.modal-backdrop').hide();

Not elegant, but effective in forcing the modal to disappear.