Leo
Leo

Reputation: 977

JavaScript append gone crazy

I am trying to build a simple 3 grid gallery, the images inside it are all with different heights and I was after a tiled gallery... So I have made one that works with a bit of JavaScript.

However, when I tried to add another gallery in the same page, something weird happened, live preview here: http://loai.directory/test/gallery

The HTML, CSS and JS can be found fully placed in this jsfiddle: http://jsfiddle.net/aY5Gu

As you can see in the live preview, all the gridElemetns in grid3 are appending to grid3 in all the threeGrid galleries! After trying to debug, I have concluded that the problem is from the JS:

//Three Grids System
   var gridElement = $(".gridElement", ".grid3");
   GalleryGrid(); $(window).resize(GalleryGrid);
   function GalleryGrid() {
      var grid3 = $('.threeGrids .grid3');
      var width = $(window).width();
      if (width < 1024 && width > 770) {
         var grid1 = $('.threeGrids .grid1');
         var grid2 = $('.threeGrids .grid2');

         for (var i = 0; i < gridElement.length; i++) {
            if (i < gridElement.length / 2) {
               grid1.append(gridElement[i]);
            } else {
               grid2.append(gridElement[i]);
            }
         }
      } else {
         grid3.append(gridElement);
      }
   }

What is going wrong? I can't seem to be able to go figure out what is wrong from there.

Upvotes: 0

Views: 58

Answers (1)

Unamata Sanatarai
Unamata Sanatarai

Reputation: 6637

That's because .threeGrids and .grid1... appear more than one time on your page. Therefore jquery automatically appends things to all of them.

Try selecting by something like:

$('.wrapper').each(
  function(){
    var grids = $(this).find('.threeGrids');
    (...do manipulation with grids...)
  }
);

This way you enter each .wrapper separately and deal with only elements that are inside it.

Upvotes: 1

Related Questions