Adding Masonry class to Jquery html string

I am trying to find and replace html data using jquery. The jquery script is working, in the fact that it is getting the html data from the one div container and replacing it with new data. The problem is on reload it is duplicating the container class and not adding the masonry-brick class needed to calculate the following divs.

Here is the JQuery:

Read More
$("div.more a").on("click", function (event) {
   event.preventDefault();
   // get the contents
    $.get(this.href, function (response) {
        // jquerify the response HTML string and find our replaceable area
        var result = $(response).find('.l-home-grid');
        // do the replace
        $('.l-home-grid').html(result);
    });
  // Revert all to original state
  $("a.active")
    .removeClass("active")
    .addClass("static");
  // Set classes to clicked anchor
  $(this)
    .removeClass("static")
    .addClass("active");

  window.location.hash = $(this).text();
});

Which is resulting in html:

<div class="mobile-padding l-home-grid masonry" style="position: relative; height: 2660px; ">
  <div class="mobile-padding l-home-grid">
    <div class="gridCells"><a href="#">
      <h4>Things</h4>
      <img width="256" height="182" src="foo.jpg"> </a></div>
    <div class="gridCells"><a href="#">
      <h4>More Things</h4>
      <img width="256" height="182" src="foo.jpg"> </a></div>
    <div class="gridCells"><a href="#">
      <h4>Objects</h4>
      <img width="256" height="182" src="foo.jpg" > </a></div>
  </div>
</div>

Why is the

<div class="mobile-padding l-home-grid masonry" style="position: relative; height: 2660px; ">
      <div class="mobile-padding l-home-grid"> 

loading twice?

The goal is this:

<div class="mobile-padding l-home-grid masonry" style="position: relative; height: 2660px; ">
    <div class="gridCells masonry-brick"><a href="#">
      <h4>Things</h4>
      <img width="256" height="182" src="foo.jpg"> </a></div>
   ...

Related posts

Leave a Reply

1 comment

  1. This is happening because you’re adding the entire .l-home-grid element from your response into your existing .l-home-grid element. Change this line:

    var result = $(response).find('.l-home-grid');
    

    to this:

    var result = $(response).find('.l-home-grid').html();
    

    in order to just add the response contents into your container. You might need to call

    $('.l-home-grid').masonry('reload');
    

    after you pull in your new content in order to make sure it gets Masonry-ified.