How I can open a materialize modal when a window is ready?

纵饮孤独 提交于 2019-12-03 21:50:30

For Materialize v0.98.2

Create a modal

<div id="modal" class="modal">
    <div class="modal-content">
      <h4>Modal Header</h4>
      <p>A bunch of text</p>
    </div>
    <div class="modal-footer">
      <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat">Agree</a>
    </div>
</div>

Open modal when a document ready load

<script>
 $(document).ready(function(){
    $('#modal').modal();
    $('#modal').modal('open'); 
 });
</script>
Léo Fasano

you can do that :

    $(document).ready(function(){
       $('.modal1').modal('open');
    });

This can be done with instance.open().

<script>
        document.addEventListener('DOMContentLoaded', function () {
            var Modalelem = document.querySelector('.modal');
            var instance = M.Modal.init(Modalelem);
            instance.open();
        });

</script>

Pure JavaScript solution.

const elem = document.getElementById('modal id here');
const instance = M.Modal.init(elem, {dismissible: false});
instance.open();

I found the solution in materialize.js We must use:

$(".MyModal").openModal()

to open modals and:

$(".MyModal").closeModal()

to close it. Materialize team forgot refresh their documentation.

In case you are still having problems given the other solutions, I had to nest the jQuery('#modal_id').modal('open') statement in a second document.ready statement like so:

jQuery(document).ready(function(){
      jQuery('#modal_id').modal();
      jQuery(document).ready(function(){
          jQuery('#modal_id').modal('open');
      });
});

I don't know why this works, and I know it's just plain ugly, but it works so..

You need to determine which event makes sense to trigger the modal to be displayed. onload or onmouseover may work for you instead of onclick.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!