Search code examples
javascriptjquerymaterialize

Materialize modal not working


I wrote a simple code for materialize modal.
HTML code:

<a class="waves-effect waves-light btn view" data-target="modal1">View Scores</a>
<!-- 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>  

JS code:

$(document).ready(function() {
  // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
  /*$('.view').click(function (){
    $('#modal1').modal('open'); 
    alert('edskjcxnm');
  });*/
  /*$('.view').leanModal();*/
  $('#modal1').modal('open');
});  

JSFiddle link: https://jsfiddle.net/7f6hmgcf/
Why isn't it working?


Solution

  • Initialize all modals first. $('.modal').modal();

    Complete code will look like this

    (function ($) {
        $(function () {
    
            //initialize all modals           
            $('.modal').modal();
    
            //now you can open modal from code
            $('#modal1').modal('open');
    
            //or by click on trigger
            $('.trigger-modal').modal();
    
        }); // end of document ready
    })(jQuery); // end of jQuery name space