Search code examples
javascriptjqueryhtmlcssmaterialize

append a div with class "modal-trigger" using jquery.append() not working


i have a modal named "modalcreatelist" using materializecss. the modal will triggered when some div is clicked using an a href tag.

<div id="modalcreatelist" class="modal"> 
  <div class="modal-content"> 
    <div class="col s12 m6 l12"> 
      <div class="row"> 
        <h6><b>Create a list..</b></h6> 
          <div class="divider"></div> <p>Title</p> 
          <input type="text" placeholder="Title.." id="listTitle"> 
          <input type="hidden" id="hiddenListId" value="<?php foreach($board as $r) {echo $r->boardId;}?>"> 
      </div> 
    </div> 
    </div> 
      <div class="modal-footer"> <a class="waves-effect waves-red btn-flat modal-action modal-close">Close</a> <a class="waves-effect waves-red btn-flat modal-action modal-close" onclick="createList()">Save</a> 
    </div> 
</div>

so i use this html code to trigger the modal, this works perfectly fine

<div id="invoice-line" class="left-align white-text">
   <a href="#modalcreatelist" class="modal-trigger white-text">Add a List..
   </a>
</div>

however when i move the code to my javascript file, i try to append the div using jquery .append() and it is not working the class "modal-trigger" is not loaded at all the url is showing like 'localhost/project#modalcreatelist'

$("#divCreateList").append'(<div id="invoice-line" class="left-align white-text"><a href="#modalcreatelist" class="modal-trigger white-text">Add a List..</a></div>')

Solution

  • You need to rebind modal-trigger after adding it to DOM. It works the first time cause the bind is done based on class name on document.ready. You need to add an event listener for click on modal-trigger and add the logic that opens your modal.

    That means, after adding the content through JavaScript. You have to write something like. $('.modal-trigger').on('click', function() { open modal; })

    replace 'open modal' with your logic.