Explain Codes LogoExplain Codes Logo

Bootstrap Modal Issue - Scrolling Gets Disabled

html
responsive-design
css
javascript
Alex KataevbyAlex Kataev·Oct 4, 2024
TLDR

You can quickly unlock scrolling in your Bootstrap Modal by managing how the modal-open class is applied and removed:

// On modal show, add super glue to the body to make modal stick $('#myModal').on('shown.bs.modal', function () { $('body').addClass('modal-open'); }); // On modal hide, remove super glue but check if other modal still needs it $('#myModal').on('hidden.bs.modal', function () { if ($('.modal.show').length) { $('body').addClass('modal-open'); // Hey, another modal needs the super glue! } });

This strategy allows the scroll to toggle as modals open and close. Make sure that no third-party scripts sabotage these events.

Preventing scroll issues in stacked modals

Ever noticed how stacked modals (opening a second while the first one is open) can sometimes lead to a scrolling headache? That's because Bootstrap gets confused and removes the modal-open class that controls scrolling. To resolve these issues, you need to put on your detective hat and revise the JavaScript event collaboration.

Stop modals from outgrowing viewport

Do your modals have a hefty diet? On consuming large content, they could exceed viewport dimensions and disable scrolling. Adjust them to stick within the viewport height:

.modal { overflow-y: auto; // liberty to scroll freely! max-height: calc(100vh - 60px); // No bigger than viewport (with a cozy padding) }

Just with these CSS styles, your modals will adhere to disciplined scrolling behavior, even when bloated with hidden content.

Dealing with content-rich modals

Real problems in our industry start with no vertical scroll bars. If your modals have large content, prompt a scroll solution with overflow-y: auto.

Rules will save the world and your code! Add the modal-open class during a hidden.bs.modal event. The class will still be there when modals are stacked. Review your modal for any hidden or unnecessary content overflow.

Handling stacked modals gracefully

When multiple modals open simultaneously, Bootstrap gets into a tangled mess of CSS classes. For an efficient "Stack Management", employ a custom JavaScript workaround to listen to modal events and manage the modal-open class as required.

Use sandbox services like Bootply to clone your problem and test its solution. Saving the Queen by killing a bug with the sword of debugging!

Staying updated and compatible

The latest versions of Bootstrap often come with improved features and bug fixes, so keeping up does pay off! Run your code in different browsers to account for unexpected behavior.