Maxime Flament Maxime Flament - 4 months ago 13
jQuery Question

Apply jQuery on dynamically generated DOMElement

I'm trying to create a masonry display with generated div blocks.
The strutcture is the following :



<div id="grid" class="panel">
<div id="grid">
<div id="posts">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/3.3.2/masonry.pkgd.js"></script>
<script src="assets/js/masonry.js"></script>

<div class="post"> <!-- The .post are generated dynamically -->
<!-- Block content generated dynamically -->
</div>
<div class="post"> <!-- The .post are generated dynamically -->
<!-- Block content generated dynamically -->
</div>
</div>
</div>
</div





And the jQuery :



jQuery(window).load(function () {



// Takes the gutter width from the bottom margin of .post

var gutter = parseInt(jQuery('.post').css('marginBottom'));
var container = jQuery('#posts');



// Creates an instance of Masonry on #posts

container.masonry({
gutter: gutter,
itemSelector: '.post',
columnWidth: '.post'
});
/*
* some code
*/
});





Each time the page is loading, I get the error : Uncaught TypeError: container.masonry is not a function.
I'm newbie in jQuery, and that's why I use a masonry template from here

I have already looked at some posts as : Event binding on dynamically created elements?
But I couldn't figure out how to solve my problem. I suppose the error occurs because I'm trying to bind events to elements which aren't created yet.

Answer

works for me... id must be unique in your markup 2 tags have same id, maybe problem with .post because empty... link to masonry.js is bad assets/js/masonry.js

jQuery(window).load(function () {



	// Takes the gutter width from the bottom margin of .post

	var gutter = parseInt(jQuery('.post').css('marginBottom'));
	var container = jQuery('#posts');



	// Creates an instance of Masonry on #posts

	container.masonry({
		gutter: gutter,
		itemSelector: '.post',
		columnWidth: '.post'
	});
});
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/3.3.2/masonry.pkgd.js"></script>
<script src="assets/js/masonry.js"></script>
<div class="panel">
  <div id="grid">
    <div id="posts">
           
      <div class="post"> 
        <p> The .post are generated dynamically</p>
        <p> Block content generated dynamically</p>
      </div>
	  <div class="post"> 
        <p> The .post are generated dynamically </p>
        <p> Block content generated dynamically </p>
      </div>
    </div>
  </div>
</div>