9

It's easy to show a modal dialog with javascript in Bootstrap.

But how to make the modal open at page load without the need of a document.ready function or a body onload function?

My need is to load a page and have the modal allready opened. I don't want a delay nor a transition effect when the page load. I want that the modal is opened at startup.

I look the modal.js a little bit and tried adding class="modal-open" on the body with no effect.

<div class="modal in" id="journalModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">modal title</h4>
      </div>
      <div class="modal-body">
         body
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

Is it possible? How to do it ?

fluminis
  • 3,575
  • 4
  • 34
  • 47

2 Answers2

13

When modal becomes visible, Bootstrap adds .in class to the it's container. So you can add a rule in your css as below and add the same class to modal - which you want to be visible at page load.

CSS

.modal.in {
   display:block;
}

HTML

<div class="modal in">visible on page load.</div>

But these will not bring the modal backdrop in place. So you gotta keep those also in bottom of page:

<div class="modal-backdrop fade in"></div>
absqueued
  • 3,013
  • 3
  • 21
  • 43
  • 1
    Works like a charm! I just had to remove the fade class for the modal backdrop not to be totally dark. `` – fluminis Jan 02 '14 at 08:01
8

Have a look at this Launch Bootstrap Modal on page load from Andres Ilich

JS

<script type="text/javascript">    
    $(window).load(function(){
        $('#myModal').modal('show');
    });
</script>
Community
  • 1
  • 1
Nishant
  • 821
  • 7
  • 17
  • 8
    The author specifically asked for a solution that doesn't require using 'the need of a `document.ready` function or a body `onload` function'. I consider `$(window).load` to be much the same as `onload`, hence the downvote. – Joel Cross Dec 23 '14 at 15:07
  • nevertheless useful for some - also $(window).load(... has to be replaced by $(windows).on('load', ....) for modern versions of jQuery. to get rid of "fade" effect just remove the "fade" class from the modal – hello_earth Aug 26 '19 at 10:12