Home > Web Front-end > JS Tutorial > How to Automatically Launch a Bootstrap Modal When the Page Loads?

How to Automatically Launch a Bootstrap Modal When the Page Loads?

Linda Hamilton
Release: 2024-10-19 15:57:01
Original
780 people have browsed it

How to Automatically Launch a Bootstrap Modal When the Page Loads?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template