简体   繁体   中英

How show bootstrap modal on window on load in javascript?

// I found it in jquery but i want it in javascript is there any alternative code. Please help, thanks

 <script type="text/javascript">

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

 </script>

I believe bootstrap toggles a class on the modal (haven't looked it up recently.

The plain JS equivalent would be

 window.addEventListener('load', () => { const modal = document.querySelector('#myModal'); if (modal) { modal.classList.add('show'); modal.style.display = 'block'; } });
 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" /> <div class="modal fade" id="myModal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">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"> <p>Modal body text goes here.</p> </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>

You may need to check the bootstrap docs to be sure what the class name it adds in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM