Launch Bootstrap Modal on page load

Brandon picture Brandon · Apr 19, 2012 · Viewed 801.3k times · Source

I don't know javascript at all. The bootstrap documentation says to

Call the modal via javascript: $('#myModal').modal(options)

I have no clue how to call this on a page load. Using the supplied code on the bootstrap page I can successfully call the Modal on an element click, but I want it to load immediately on a page load.

Answer

Andres Ilich picture Andres Ilich · Apr 19, 2012

Just wrap the modal you want to call on page load inside a jQuery load event on the head section of your document and it should popup, like so:

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>

You can still call the modal within your page with by calling it with a link like so:

<a class="btn" data-toggle="modal" href="#myModal" >Launch Modal</a>