[javascript] 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.

This question is related to javascript html twitter-bootstrap

The answer is


Update 2020 - Bootstrap 5

Building on the excellent responses from previous answers, in Bootstrap 5 with no jQuery, this has worked;

document.querySelector('[data-target="#exampleModal"]').click();

Full snippet:

_x000D_
_x000D_
window.onload = () => {
  document.querySelector('[data-target="#exampleModal"]').click();
}
_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" rel="stylesheet" />


<div class="container py-3">

  <!-- Button trigger modal -->
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
    Launch demo modal
  </button>

  <!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>

</div>
_x000D_
_x000D_
_x000D_


In addition to user2545728 and Reft answers, without javascript but with the modal-backdrop in

3 things to add

  1. a div with the classes modal-backdrop in before the .modal class
  2. style="display:block;" to the .modal class
  3. fade in together with the .modal class

Example

<div class="modal-backdrop in"></div>

<div class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="channelModal" style="display:block;">

    <div class="modal-dialog modal-lg" role="document">

        <div class="modal-content">

            <div class="modal-header">

                <h4 class="modal-title" id="channelModal">Welcome!</h4>

            </div>

            <div class="modal-body" style="height:350px;">

                How did you find us?

            </div>

        </div>

    </div>

</div>

You can try this runnable code-

_x000D_
_x000D_
$(window).load(function()_x000D_
{_x000D_
    $('#myModal').modal('show');_x000D_
});
_x000D_
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        </div>_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

More can be found here.

Think u have your complete answer.


In my case adding jQuery to display the modal didn't work:

$(document).ready(function() {
    $('#myModal').modal('show');
});

Which seemed to be because the modal had attribute aria-hidden="true":

<div class="modal fade" aria-hidden="true" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

Removing that attribute was needed as well as the jQuery above:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

Note that I tried changing the modal classes from modal fade to modal fade in, and that didn't work. Also, changing the classes from modal fade to modal show stopped the modal from being able to be closed.


You don't need javascript to show modal

The simplest way is replace "hide" by "in"

class="modal fade hide"

so

class="modal fade in"

and you need add onclick = "$('.modal').hide()" on button close;

PS: I think the best way is add jQuery script:

$('.modal').modal('show');

In order to avoid bootstrap being overruled and loosing it´s funcionality, simply create a regular launch button, provide it with an Id, and 'click it' using jquery, like so: The launch button:

<button type="button" id="btnAnouncement" class="btn btn-primary" data-toggle="modal" data-target="#modalAnouncement">
  See what´s new!
</button>

The jQuery trigger:

$(document).ready(function () {
  $('#btnAnouncement').click();
)}

Hope it helps. Cheers!


In bootstrap 3 you just need to initialise the modal through js and if in the moment of the page load the modal markup is in the page the modal will show up.

In case you want to prevent this, use the option show: false where you initialise the modal. Something like this: $('.modal').modal({ show: false })


Tested with Bootstrap 3 and jQuery (2.2 and 2.3)

$(window).on('load',function(){
  $('#myModal').modal('show');
});



<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title"><i class="fa fa-exclamation-circle"></i>&nbsp; //Your modal Title</h4>
        </div>
        <div class="modal-body">
          //Your modal Content
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
        </div>
      </div>

    </div>
</div>

https://jsfiddle.net/d7utnsbm/


You can activate the modal without writing any JavaScript simply via data attributes.

The option "show" set to true shows the modal when initialized:

<div class="modal fade" tabindex="-1" role="dialog" data-show="true"></div>

You may want to keep jquery.js deferred for faster page load. However, if jquery.js is deferred the $(window).load may not work. Then you may try

setTimeout(function(){$('#myModal').modal('show');},3000);

it will popup your modal after page is completely loaded (including jquery)


I recently needed to launch a Bootstrap 5 modal without jQuery and not with a button click (eg, on page load) using Django messages. This is how I did it:

Template/HTML

<div class="modal" id="notification">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Notification!</h5>
        <button type="button" class="btn-close"
                data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        {% for m in messages %}
          {{ m }}
        {% endfor %}
      </div>
      <div class="modal-footer justify-content-between">
        <a class="float-none btn btn-secondary" href="{% url 'some_view' %}"
           type="button">
          Link/Button A
        </a>
        <button type="button" class="btn btn-primary"
                data-bs-dismiss="modal">
          Link/Button B
        </button>
      </div>
    </div>
  </div>
</div>

JS in a file or in the template

{% block javascript %}
  {{ block.super }}
  <script>
    var test_modal = new bootstrap.Modal(
      document.getElementById('notification')
    )
    test_modal.show()
  </script>
{% endblock javascript %}

This method will work without the Django template; just use the HTML and put the JS in a file or script elements that loads after the Bootstrap JS before the end of the body element.


Like others have mentioned, create your modal with display:block

<div class="modal in" tabindex="-1" role="dialog" style="display:block">
...

Place the backdrop anywhere on your page, it does not necesarily need to be at the bottom of the page

<div class="modal-backdrop fade show"></div> 

Then, to be able to close the dialog again, add this

<script>
    $("button[data-dismiss=modal]").click(function () {
        $(".modal.in").removeClass("in").addClass("fade").hide();
        $(".modal-backdrop").remove();
    });
</script>

Hope this helps


<div id="ModalStart" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-body">
          <p><i class="icon-spinner icon-spin icon-4x"></i></p>
    </div>
</div>

You can show it on start even without Javascript. Just delete the class "hide".

class="Modal"

Update 2020 - Bootstrap 4

The modal markup has changed slightly for Bootstrap 4. Here's how you can open the modal on page load, and optionally delay display of the modal...

$(window).on('load',function(){
    var delayMs = 1500; // delay in milliseconds

    setTimeout(function(){
        $('#myModal').modal('show');
    }, delayMs);
});    

<div class="modal fade" id="myModal">
      <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">My Modal</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary mx-auto" data-dismiss="modal">Close</button>
                </div>
            </div>
      </div>
</div>

Demo on Codeply


Heres a solution [without javascript initialization!]

I couldn't find an example without initializing your modal with javascript, $('#myModal').modal('show'), so heres a suggestion on how you could implement it without javascript delay on page load.

  1. Edit your modal container div with class and style:

<div class="modal in" id="MyModal" tabindex="-1" role="dialog" style="display: block; padding-right: 17px;">

  1. Edit your body with class and style:

    <body class="modal-open" style="padding-right:17px;">

  2. Add modal-backdrop div

    <div class="modal-backdrop in"></div>

  3. Add script

    $(document).ready(function() {
        $('body').css('padding-right', '0px');
        $('body').removeClass('modal-open');
        $('.modal-backdrop').remove();
    
        $('#MyModal').modal('show'); });
    

    What will happen is that the html for your modal will be loaded on page load without any javascript, (no delay). At this point you can't close the modal, so that is why we have the document.ready script, to load the modal properly when everything is loaded. We will actually remove the custom code and then initialize the modal, (again), with the .modal('show').


regarding what Andre's Ilich say you have to add the js script after the line in what you call the jquery:

<script src="content/bootstrapJS/jquery-2.1.1.min.js" type="text/javascript"></script>

<script type="text/javascript">
     $(window).load(function(){
         $('#myModal').modal('show');
      });
</script>

in my case that was the problem hope it helps


Just add the following-

class="modal show"

Working Example-

_x000D_
_x000D_
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal show" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        </div>_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation