MaterializeCss modal Error openModal is not a function

10,383

Solution 1

Materialize functions needs Jquery Elements.
getElementById() - Gives us DOM Object.

//You can either convert this Dom object to Jquery

var modal = document.getElementById('modal1');
var jquerymodal = $(modal);  //convert to jQuery Element
jquerymodal.openModal();


//Or just use Jquery Element like

$('#modal1').openModal();

Solution 2

Ok I had the same issue and I fixed it by changing up the call to open the modal and the initialization.

If you had the same issue as I, check out the most recent documentation here

This may be new - openModal() is not used here.

Initialization:

<script>
   try {
       try {
      $('#modalId').modal();
  } catch (e) {
      console.info('loading modal auto-initialized..');
  }
   }
</script>

I added the try/catch because sometimes this is not needed

Implementation:

$('#modalID').modal('open');
Share:
10,383
Ricki Moore
Author by

Ricki Moore

Updated on June 13, 2022

Comments

  • Ricki Moore
    Ricki Moore almost 2 years

    I have all requirements Jquery, Materialize.js sitting above my Js file however I get the warning openModal is not a function..I checked the modal name is right and I can run Materialize.toast so I know Materialize.js is working. Triggering with the button does not call the modal either. Here is the code..

    Scripts:

    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="/js/materialize.js"></script>
    <script type="text/javascript" src="/js/video.js"></script>
    <script src="/js/admin.js"></script>
    

    Trigger:

    <button data-target="modal1" class="btn modal-trigger">Modal</button>
    

    Modal:

        <!-- Modal Structure -->
        <div id="modal1" 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>
    </div>
    

    js:

     var modal = document.getElementById('modal1');
      modal.openModal();
    $('#modal1').leanModal();
    $('#modal1').openModal();
    
  • Ricki Moore
    Ricki Moore over 7 years
    I tried to give it Jquery as well didn't accept that either. Responds: Uncaught TypeError: $(...).openModal is not a function