Explain Codes LogoExplain Codes Logo

Calling a function on Bootstrap modal open

javascript
event-handling
modal
bootstrap
Anton ShumikhinbyAnton Shumikhin·Jan 31, 2025
TLDR

Bind a function to a Bootstrap modal's show.bs.modal to have it run just before the modal opens:

$('#yourModal').on('show.bs.modal', function() { myFunction(); // Replace with your function });

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:

$('#yourModal').on('shown.bs.modal', function() { console.log("I'm the king of the world!"); // This could be your function });

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:

$(document).on('shown.bs.modal', '#yourModal', function() { console.log("Look ma, I'm dynamic!"); // Your function here });

Handling modal closure

The hidden.bs.modal event can be used for cleanup tasks after the modal has closed:

$('#yourModal').on('hidden.bs.modal', function() { console.log("Clean as a whistle!"); // Your cleanup function here });

Controlling execution timing

Prefer your function to kick in just before the modal shows up? Use the show.bs.modal event:

$('#yourModal').on('show.bs.modal', function(e) { console.log("Spotted an iceberg!"); // Function to run before modal is shown });

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:

$(window).on('shown.bs.modal', function() { console.log("All the world's a stage, and all the men and women merely players."); // Global function here });

Debug using console or alert

It's a simple yet effective way to ensure your functions are running as expected:

$('#yourModal').on('shown.bs.modal', function() { console.log("Not all who wander are lost."); // A hint to your users });

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.