Blog · 07/01/2021

Bootstrap: stacked modals and scroll issues

When we are using Bootstrap you may have ever had the need to drive several Modals, i.e. that one Modal appears over another Modal.

If you have found the problem that after the 2nd Modal appears and then close it, the 1st Modal has already lost the ability to Scroll, I have found a pretty simple solution.

$(document).on('hidden.bs.modal', function (event) {
  if ($('.modal:visible').length) {
    $('body').addClass('modal-open');
  }
});

Quick Fix: Scrolling and Focus when multiple bootstrap modals are open – James' Desk (wordpress.com)

The code is activated after hiding any Modal, then check if there is any Visible Modal and adds to the visible Modal the "modal-open" class which returns the functionality of the scroll.

The "modal-open" class is removed from all the modals, although they are open after closing any modal, so it causes the failure of the scroll in the modal that remains visible.

For Bootstrap that modal that is still visible without the "modal-open" class will recognize it as "closed", so the scroll remains unused.

The solution of this code is always to check if there is any visible modal after closing any modal and add the "modal-open" class so that Bootstrap understands that modal remains open and consequently that it continues to function perfectly the scroll.

In this way we get to activate the 1st Modal, after closing the 2nd Modal, so that we get back to the ability to scroll.

It’s a very simple solution, just you’ll have to put the previous code fragment in a main.js file, so that when the page is loaded, the event is registered and can run whenever necessary.

This solution has been useful to you, if you have a better solution, comment on it!