Load Bootstrap modal on page load without firing button or using jQuery

Viewed 71952

I'm trying to launch a Bootstrap modal on page load without firing a HTML button or using jQuery.

Here's my code:

<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap-theme.min.css">
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>

<div id="my-modal" class="modal fade">
    <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">Title</h4>
            </div>
            <div class="modal-body">
                Hello World!
            </div>
        </div>
    </div> 
</div>

This works when you call

$('#my-modal').modal('show');

But I don't want to call a method or fire a button. Is there a way to launch modal automatically on page load?

Demo: Fiddle

7 Answers

On Bootstrap 5, just create a modal variable with options and runs it with .show()

var myModal = new bootstrap.Modal(document.getElementById('modal'), {keyboard: false, backdrop: 'static'});
myModal.show();

Without Jquery, you cannot use this;

myModal.modal('show');

On Bootstrap 4 --

Add the show class to your modal

<div class="modal fade show" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

and following css --

.modal {
    display:block;
  }

On bootstrap 5 and don't use Jquery here my answer;

First we assign an id to the button, select to button and then when page load click automatically this button.

document.getElementById("btn-my").click();

and in css;

#btn-my {
display: none;
}

That's it.

Related