Search code examples
javascripthtmlmaterialize

Materialize css modal not working through JS innerHTML insertion


I'm trying to insert a Materialize CSS modal with JS innerHTML function but the modal doesn't work anymore not sure why. It works when normally in the document though.

  $(document).ready(function(){
    $('.modal-trigger').leanModal();
    insertModal();
  });

function insertModal(){
  var html = '';
  html += '<div class="col"><a class="waves-effect waves-light btn modal-trigger" href="#modal1">Modal</a> </div>';
  //Modal Structure
  html += '<div id="modal1" class="modal">';
  html += '<div class="modal-content"><h4>Modal Header</h4><p>A bunch of text</p></div>';
  html += '</div>';
  document.getElementById('modal-test').innerHTML = html;
}

Here is the demo I've of the issue im encountering https://codepen.io/RelativeBinary/pen/YBbmrg?editors=1010

I plan to have a loop which will insert a bunch of modals based on an array of objects, so each modal would contain different information, which is why im inserting from JS, so i don't have to manually type out each modal for each different object.

Any suggestions would be appreciated.

PS: Demo is fixed, still represents the issue but reflects the actual reason why it wasnt working better.


Solution

  • You are doing everything fine. I am not sure why you are using leanModal for materialize css modals but you when you insert any new javascript component what actually would work is you need to reinitialize that component. As in the below codepen i have reinitialize the modal in the bottom of your function and it work fine.

    https://codepen.io/bilal-ahmad/pen/vbqWrd?editors=1010

    <div id="modal-test" class="row section">
    </div>
    
      $(document).ready(function(){
        insertModal();
      });
    
    function insertModal(){
        var html = '';
        html += '<div class="col"><a class="waves-effect waves-light btn modal-trigger" href="#modal1">Modal</a> </div>';
       //Modal Structure
       html += '<div id="modal1" class="modal">';
       html += '<div class="modal-content"><h4>Modal Header</h4><p>A bunch of text</p></div>';
       html += '</div>';
       document.getElementById('modal-test').innerHTML = html;
       $('.modal').modal();
    }
    

    As you mention you are loading modals in a loop so I suggest to initialize the modal at the end of the loop where you load all of your modals and then initialize the modal.

    Note: Please also update your materialize css js file link it looks outdated.