Home >Web Front-end >JS Tutorial >How to Launch a Bootstrap Modal Automatically on Page Load?

How to Launch a Bootstrap Modal Automatically on Page Load?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 15:59:021033browse

How to Launch a Bootstrap Modal Automatically on Page Load?

Launch Bootstrap Modal 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">&times;</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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn