Home >Web Front-end >JS Tutorial >How to Launch a Bootstrap Modal Automatically on Page Load?
Bootstrap provides a simple way to create modal pop-ups, but it requires some basic JavaScript knowledge. For beginners, this can be daunting, especially when trying to launch a modal on page load directly.
Understanding the Documentation
The Bootstrap documentation suggests calling the modal with $('#myModal').modal(options). However, determining how to use this code for a page load scenario can be confusing.
Solution
To launch a Bootstrap modal immediately upon page load, wrap it within a jQuery load event in the
section of your document. This will automatically trigger the modal when the page is loaded.<code class="html"><script type="text/javascript"> $(window).on('load', function() { $('#myModal').modal('show'); }); </script></code>
Ensure that your HTML includes the modal with the necessary classes and structure:
<code class="html"><div class="modal hide fade" id="myModal"> <!-- Modal Header --> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> <h4 class="modal-title">Modal title</h4> </div> <!-- Modal Body --> <div class="modal-body"> ... </div> <!-- Modal Footer --> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div></code>
While this method automatically opens the modal on page load, you can still trigger the modal manually using a button or link with the following code:
<code class="html"><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"> Launch Modal </button></code>
The above is the detailed content of How to Launch a Bootstrap Modal Automatically on Page Load?. For more information, please follow other related articles on the PHP Chinese website!