Calling a function on Bootstrap modal open
Bind a function to a Bootstrap modal's show.bs.modal to have it run just before the modal opens:
Ensure '#yourModal' matches your modal's ID. This myFunction runs just before the modal is shown.
Detailed walkthrough
Executing function when modal is visible
Here we're binding to the shown.bs.modal event for the function to be executed right after the modal is made visible:
Please remember, for Bootstrap versions before 3.0, use the shown event instead.
Dealing with dynamic content
Modal contents dynamically loaded via AJAX or similar methods may require delegated event handler:
Handling modal closure
The hidden.bs.modal event can be used for cleanup tasks after the modal has closed:
Controlling execution timing
Prefer your function to kick in just before the modal shows up? Use the show.bs.modal event:
Additional considerations
Windows for global events
Sometimes, it's helpful to bind the event to $(window) if you're manipulating all modals on a page:
Debug using console or alert
It's a simple yet effective way to ensure your functions are running as expected:
Keeping code concise
Keep modal-specific functions lean and mean, ensuring each bit of code serves a direct purpose.
Future-proof your code
Consider forward-compatibility and ease of maintenance for your modal workflows while you're implementing your current solution.
Was this article helpful?