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

38,762

Solution 1

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.

Solution 2

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>

Solution 3

Pure JavaScript solution.

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

Solution 4

you can do that :

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

Solution 5

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>
Share:
38,762
Martin Rafael Pérez Lara
Author by

Martin Rafael Pérez Lara

Updated on April 28, 2020

Comments

  • Martin Rafael Pérez Lara
    Martin Rafael Pérez Lara about 4 years

    I want to open a modal window when the user be in a window, I mean, open a modal without a trigger button, I have this example.

    <button data-target="modal1" class="btn modal-trigger" id="btn-1">Modal</button>
    <div id="modal1" class="modal modal-fixed-footer">
    <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>
    

    It works if I click on the trigger button, but I don't want a click. I use this code when the window is ready:

    $(function()
    {
        function checkCode()
        {
            $("#btn-1").click();
        }
    });
    

    This automatically push the button and make the effect that modal is auto opened, but I don't want to do this.

  • Léo Fasano
    Léo Fasano over 7 years
    You can also use the $('yourModal').modal('open') function on every event top open 'yourModal'
  • Martin Rafael Pérez Lara
    Martin Rafael Pérez Lara over 7 years
    I've tried that, but I receive an error: $(...).modal() is not a function :( I had to use $(...).leanModal()
  • Bilal Ahmad
    Bilal Ahmad about 5 years
    i see this is the issue with materialize js components. You need to initialize the components separately.
  • Joseph Cardwell
    Joseph Cardwell about 5 years
    @BilalAhmad can you elaborate please?