289

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.

Amal K
  • 4,359
  • 2
  • 22
  • 44
Brandon
  • 3,019
  • 2
  • 14
  • 6
  • 15
    @rlemon - Not necessarily; the question was strictly about Bootstrap modal and not running functions upon page load in general. Bootstrap modal can be manipulated via CSS classes as well, see one of the answers. – Miro Feb 21 '14 at 10:57
  • this will help.simpler: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_dialog_showmodal with onload event – user2290820 Oct 29 '15 at 13:47

21 Answers21

523

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>
Mootje
  • 127
  • 9
Andres I Perez
  • 75,075
  • 21
  • 157
  • 138
  • 21
    This answer is correct. One thing to note is that this will NOT work at all on the document ready event: `$(document).ready( ... `. It will only work on the window load event: `$(window).load( ... `. – racl101 Aug 12 '14 at 22:54
  • 5
    Another important note: a lot of people post their javascript includes at the end of the body. in which case, the onload function must be included at the end, after the includes. – Adam Joseph Looze Mar 01 '15 at 19:19
  • @racl101 It's the opposite for me (it's been 2 years since your post, so things might have changed). It only works with `$(document).ready( ...` when I store this script in an MVC PartialView for my Modal that is dynamically added when a user clicks on something, so maybe that's why. Ironically, your warning of what _not_ to do allowed me to figure out how to make it work for me. So thanks? :) – MikeTeeVee Jul 22 '16 at 08:48
  • Hide didn't work for me (as class), since bootstrap overruled it and therefore wouldn't show anything. It looked terrible (not like a modal) and it also didn't close when you pressed the button. The javascript part worked, but I would suggest to use the html part of the modal that GAURAV MAHALE used in his answer, but note to remove the word 'show' in the class of his modal. – Malachi Jan 18 '18 at 20:47
  • Just include jQuery Library first ! – ersks Mar 10 '18 at 07:45
  • @racl101 works in 2020 tho: $(document).on('ready',function() ... – EvilSmurf Feb 19 '20 at 09:03
  • Only works for me if I go `$('#myModal').modal();` – Jonathan Willcock Jul 18 '23 at 12:55
95

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');
Peon
  • 7,902
  • 7
  • 59
  • 100
user2545728
  • 1,013
  • 7
  • 3
  • 2
    I've tried this method but get two issues. 1) the modal won't close. 2) The modal background has disappeared. Any ideas? – Nick Green Jul 25 '14 at 10:15
  • 2
    The jquery solution above works nicely. One line of code does the trick. @NickGreen Give this a try: class="modal fade". Remove 'hide' and 'in'. This works in my case but it's not live yet, otherwise I'd post the link. – Randy Greencorn Apr 08 '15 at 19:02
45

Just add the following-

class="modal show"

Working Example-

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div class="container">
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal show" 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">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
      
    </div>
  </div>
  
</div>
Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
GAURAV MAHALE
  • 1,032
  • 10
  • 18
27

You can try this runnable code-

$(window).load(function()
{
    $('#myModal').modal('show');
});
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div class="container">
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- 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">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
      
    </div>
  </div>
  
</div>

More can be found here.

Think u have your complete answer.

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
26

Update 2021

Bootstrap 5

Now that Bootstrap no longer requires jQuery, it's easy to show the modal using JavaScript..

var myModal = new bootstrap.Modal(document.getElementById('myModal'), {})
myModal.toggle()

Demo

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

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
  • 1
    Alternatively, you can use the "data-show" attribute: https://getbootstrap.com/docs/4.5/components/modal/#via-data-attributes – Mike Jun 09 '20 at 17:34
11

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

<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.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

ethry
  • 731
  • 6
  • 17
JPCS
  • 311
  • 2
  • 8
7

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/

Felipe Lima
  • 443
  • 1
  • 10
  • 19
  • 1
    @EduardoCuomo yes, it work's https://jsfiddle.net/bsmpLvz6/ This example was made using Bootstrap 3.3 and jQuery 2.2 – Felipe Lima Jun 07 '18 at 20:21
6

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.

Highly Irregular
  • 38,000
  • 12
  • 52
  • 70
6

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>
obiTheOne
  • 105
  • 2
  • 5
  • doesn't work for me on bootstrap 5 latest. – dqhendricks Jul 02 '22 at 22:24
  • @dqhendricks I did a couple of tests, but this feature seems to have been removed from bootstrap 5. – obiTheOne Aug 11 '22 at 09:53
  • yeah, I eventually started tagging the ones I needed open with a class and using javascript to "show" any modals marked with that class on page load. not ideal compared to this, but works fine. I found other solutions messing directly with styles, but they would break the modal's "close" functionality. – dqhendricks Aug 11 '22 at 21:24
5

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').

Reft
  • 2,333
  • 5
  • 36
  • 64
5

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

jBelanger
  • 1,526
  • 18
  • 11
4

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>
RafaSashi
  • 16,483
  • 8
  • 84
  • 94
3
<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"
SPIELER
  • 1,703
  • 1
  • 9
  • 7
3

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:

window.onload = () => {
  document.querySelector('[data-target="#exampleModal"]').click();
}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/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>
David Lemayian
  • 2,679
  • 1
  • 20
  • 18
  • 1
    what you have can't work for the current version of bootstrap `window.onload = () => { document.querySelector('[data-bs-target="#exampleModal"]').click(); }` is the correct one at the moment – Nazehs Nov 24 '21 at 15:47
3

you can using jQuery to handle this

first import on your template

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

and hit the id on your modal with jQuery Script

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

here is the modal for case display django message

{% if messages %}
      {% for message in messages %}
      <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="false">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="staticBackdropLabel">Message</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              {{ message }}
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
          </div>
        </div>
      </div>
      {% endfor %}
        
    {% endif %}
perymerdeka
  • 766
  • 9
  • 19
2

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 })

Stafie Anatolie
  • 358
  • 2
  • 12
1

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.

nicorellius
  • 3,715
  • 4
  • 48
  • 79
  • i use django too, but my bootstrap is not defined, how to import it? – perymerdeka Jan 05 '22 at 15:31
  • You would set up BS according to their docs: https://getbootstrap.com/docs/5.0/getting-started/introduction/. In my case, my `base.html` template defines all my CSS and JS in other templates, as needed, then I use the `block.super` variable to inject additional JS. But you can do this by putting the JS in a separate JS file, loaded at page load too, if youw ant. – nicorellius Jan 06 '22 at 16:39
1

maybe it's late but, once I was not able to solve this order issue, and modal was not getting shown; I used jquery click();

I tried this and it worked well :)

create a button, which calls Modal show > style that button as display : none; Example :

 


$( "#clickme" ).click();
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<input type="button" value="0"  id="clickme" style="display:none;" data-toggle="modal" data-target="#exampleModal" />   
<!-- Modal -->
<div id="exampleModal" class="modal" 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">Clicked Successfully</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

</body></html>
Shubham Dange
  • 173
  • 13
0

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)

JH_
  • 406
  • 1
  • 4
  • 15
Viktor Ka
  • 276
  • 3
  • 5
  • 4
    Setting a timeout for the DOM to be ready is the ultimate bad practise.. What if the user has a slow connection? Than it could take 10 seconds.. So never NEVER do this – DutchKevv Jul 15 '16 at 11:35
0

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!

E. Barney
  • 373
  • 4
  • 19
0

In JS:

<script>

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

</script>

Boostrap Modal in HTML:

        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Alert</h4>
          </div>
          <div class="modal-body">
            <p><?= session('msg') ?></p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>

      </div>
    </div>

replace myModal with your's

JWC May
  • 605
  • 8
  • 14