AI Bootstrap Builder Logo
AI Bootstrap Builder Questions & Answers

How do I create a modal that opens automatically when the page loads in Bootstrap 5?

Asked on Jun 01, 2025

1 Answer

To create a modal that opens automatically when the page loads in Bootstrap 5, you can use JavaScript to trigger the modal's show method once the DOM is fully loaded.
<!-- BEGIN COPY / PASTE -->
        <!-- Modal HTML -->
        <div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="myModalLabel">Modal title</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        This is the modal content.
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- JavaScript to open modal on page load -->
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                var myModal = new bootstrap.Modal(document.getElementById('myModal'), {});
                myModal.show();
            });
        </script>
        <!-- END COPY / PASTE -->
Additional Comment:
  • Ensure you include Bootstrap's CSS and JS files in your project.
  • The modal is triggered to show once the DOM content is fully loaded using the `DOMContentLoaded` event.
  • The `bootstrap.Modal` constructor is used to create a new modal instance, and the `show` method is called to display it.
✅ Answered with Bootstrap 5 best practices.
← Back to All Questions