How to Automatically Launch a Bootstrap Modal on Page Load
Bootstrap offers versatile modal windows to enhance user interactions. As a beginner in JavaScript, you may encounter challenges activating modals on page load. Let's delve into a practical approach to addressing this need.
According to Bootstrap documentation, modals can be invoked via JavaScript using the '$('#myModal').modal(options)' syntax. However, the documentation doesn't explicitly detail how to activate the modal on page load.
To resolve this, embed the modal within a jQuery load event placed in the head section of the document. This ensures that the modal pops up as soon as the page finishes loading. Here's an example:
JS
<script type="text/javascript"> $(window).on('load', function() { $('#myModal').modal('show'); }); </script>
HTML
<div class="modal hide fade" id="myModal"> <div class="modal-header"> <a class="close" data-dismiss="modal">×</a> <h3">Modal header</h3> </div> <div class="modal-body"> <p>One fine body…</p> </div> <div class="modal-footer"> <a href="#" class="btn">Close</a> <a href="#" class="btn btn-primary">Save changes</a> </div> </div>
With this setup, the modal will automatically appear when the page loads. Additionally, you can still invoke the modal through a trigger element (e.g., a link):
<a class="btn" data-toggle="modal" href="#myModal">Launch Modal</a>
In summary, embedding the modal within a jQuery load event provides a straightforward way to display modals immediately on page load, even for JavaScript beginners.
The above is the detailed content of How to Automatically Launch a Bootstrap Modal When the Page Loads?. For more information, please follow other related articles on the PHP Chinese website!