Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch Bootstrap Modal on Page Load

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.

like image 606
Brandon Avatar asked Sep 26 '22 16:09

Brandon


People also ask

How do you trigger a modal on page load?

Answer: Use the Bootstrap . modal('show') method modal('show') method for launching the modal window automatically when page load without clicking anything. A common example of this technique is loading the modal when user landed on the home page and requesting them to subscribe the website newsletter.

How do I link modal to another page?

To make it work, first remove the data-target and data-toggle attributes from the link. You can leave the href attribute there. Using jQuery we can add a click listener to the <a> element, but we do not want to directly go to the page indicated by the href attribute so we use preventDefault() .


1 Answers

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>
like image 508
Andres Ilich Avatar answered Oct 17 '22 23:10

Andres Ilich