javascripthtmlmaterializedom-manipulationinsertadjacenthtml

JavaScript insertAdjacentHTML Opening a new modal isn't working


I'm trying to get a modal to open using insertAdjacentHTML so the issue Is insertAdjacentHTML modal isn't opening when inserted onto the DOM. I can only assume I'm missing a simple concept. please help :)

// ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', function() {
  let elems = document.querySelectorAll('.modal');
  let instances = M.Modal.init(elems);
});


// Add Extra Colums
const addMoreBtn = document.getElementById("addmorebtn");
const addColums = document.getElementById("addcolumns");

addMoreBtn.addEventListener('click', (e) => {
e.preventDefault();

  const first = 
  `
<div id="addcolumns">
<!--  Button / Modal / Form Inputs -->
<!--  Button  -->
 <div class="row">
  <div class="col s12 center">
    <a href="#exercise1" class="disabled-exersice-btn btn-floating btn-small darken-4 z-depth-2 black center modal-trigger">
      <i class="material-icons white-text">add </i>
    </a>
  </div>
 <!--  Modal  -->
 <div class="modal modal-position" id="exercise1">
  <div class="valign-wrapper center-align">
   <div class="row">
    <form class="exercises-form col s12 valign-wrapper center-align" autocomplete="off">
      <div class="input-field">     
        <input type="text" placeholder="Exercise:" id="autocomplete-input" class="autocomplete center">
        <label for="autocomplete-input"></label>
        <div class="removebtn-padding">
          <input class="modal-close btn black" type="submit" value="Submit">
       </div> 
      </div>
    </form>
   </div>     
  </div>
</div>

</div>
     `
   const position = "afterend";
   addColums.insertAdjacentHTML(position, first);
});


Solution

  • You'll need to initialise any new modals that get added to to DOM after they are added.

    var elems = document.querySelectorAll('.modal');
    var instances = M.Modal.init(elems);