Matt G
Matt G

Reputation: 248

Appending clones of element is causing page to not load

I have several div elements on my page, and I want it so that when you click one, it opens up in a modal. To accomplish this, I am using Javascript to clone and then append each element to a bootstrap modal. The problem is, whenever I try to append the copied div to the modal, either using clone or by copying the outerHTML, the page wont load, and I have to force-quit the tab.

for (var i = 0; i < projects.length; i++) {
var p = projects[i];

// Create modal container
var outerModal = document.createElement('div');
outerModal.id = p.id + "-modal";
outerModal.className += " modal fade";  
outerModal.setAttribute("role", "dialog");

var innerModal = document.createElement('div');
innerModal.className += " modal-dialog";

var p2 = p.cloneNode(true);
innerModal.appendChild(p2);
//console.log(p2);
outerModal.appendChild(innerModal);
document.body.appendChild(outerModal);
p.onclick = function(){$(outerModal).modal("show");};
}

What is causing this? I assume something is taking up too much memory or something, but I dont see where.

Upvotes: 0

Views: 48

Answers (2)

Brandon
Brandon

Reputation: 3266

Instead of creating multiple modals, do this:

  1. Create one modal
  2. On each of your div, add a click event that passes in the ID.
  3. In the click event, run a switch/case on it and populate that one modal based on the clicked div

Upvotes: 1

John-Paul Ensign
John-Paul Ensign

Reputation: 141

If you're using Chrome you can press Shift+Escape to check memory usage. Also, using console.log to check what it is doing can be pretty helpful.

Can you provide a demo? Something like jsfiddle or similar. I created a quick test page and this appears to be working as far as creating divs with the proper classes.

Here is a JSFiddle example: https://jsfiddle.net/g9m2w98j/

HTML

<div id="outerModal" class="modal fade" role="dialog">
  <div id="innerModal" class="modal-dialog">
    <div id="modalContent" class="modal-content">

    </div>
  </div>
</div>

<div>
  <h2>
    Text Elements
  </h2>
  <input type="text" name="project" value="Test1"> <br>
  <input type="text" name="project" value="Test2"> <br>
  <input type="text" name="project" value="Test3"> <br>
  <input type="text" name="project" value="Test4"> <br>
  <input type="text" name="project" value="Test5"> <br>
</div>

</body>

JavaScript

$("[name = 'project']").on('click', function(){
    $('#modalContent').empty();
    $('#modalContent').append($(this).clone(true));
  $('#outerModal').modal("show");
});

CSS

.modal-content {
  padding: 15px;
}

Upvotes: 0

Related Questions