MaterializeCss modal Error openModal is not a function

老子叫甜甜 提交于 2019-12-05 22:24:42

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();

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');

Import the minified file in materialize/dist folder instead of materialize/js.

Run with: $('#elementId').modal(); $('#elementId').modal('show');

Just this way it worked.

EDIT:

In fact, it didn't work in production environment.

So I did this:

(function( $ ) {

    $.fn.showModal = function() {

        var self = this;
        try {
            this.modal();
            self.modal('open');
        } catch (err) {
            try{
                self.openModal();
            } catch (err2) {
                console.error("Something went wrong - cannot open modal.");             
            }
        }
    }


    $.fn.hideModal = function() {

        var self = this;
        try {
            this.modal();
            self.modal('close');
        } catch (err) {
            try{
                self.closeModal();
            } catch (err2) {
                console.error("Something went wrong - cannot close modal.");                
            }
        }
    }


}( jQuery ));

Use just: $('#modal').showModal()

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