-1

I have a masonry gallery with ul / li elements. To make them responsive I am adding to each 'li' element it's column number as a class, so I can sort them later.

I am trying to get previous elements height in column before adding new one. So basically the column height before new 'li' element.

I am using prevAll(), to get all previous elements, but I can't combine height calculation and filtering columns. So tried to achieve it with each(), with filter, and with changing selector, I added that part of the code.

var that= this;
that.prevAll = $(this).prevAll();


that.top += $(this).prevAll('.column' + that.current_column).height(); 
// selector

that.top += that.prevAll.filter('.column' + that.current_column).height(); 
// filter

that.prevAll.each(function(){
  if(that.prevAll.hasClass('.column' + that.current_column)) {
  that.top += that.prevAll.height() + that.settings.imegesGap;
 };            
});
// .each

DOM

jQuery

 $this.addClass('column' + that.current_column);
 $this.addClass('row' + that.row);

HTML

<ul class="mosaic1">
    <li ><img src="img/test.png"></li>
    <li ><img src="img/test6.jpg"></li>
    <li ><img src="img/test4.jpg"></li>
    <li ><img src="img/test.3.jpg"></li>
    <li ><img src="img/test7.jpg"></li>
    <li ><img src="img/test5.png"></li>
</ul>

The main problem with 'each' function.It keeps summing up.

P.S. This is my first question here, so sorry if description not good enough.

Davit Mkrtchyan
  • 449
  • 5
  • 15
  • Looks like you're giving an invalid selector to both the `prevAll()` and `filter()` calls. – Taplar May 27 '19 at 14:46
  • Please provide your DOM structure as well. `column` selector is not a valid selector. It should either be `#myId` or `.myClassName` or `button` (last one could be any element name). If *column* would be a class, it would look like: `.prevAll(".column")` or `.prevAll(".column " + that.current_column)` – Barrosy May 27 '19 at 14:51
  • Thank you so much, it was a mistake in here, but the code was fine, I updated my question. – Davit Mkrtchyan May 27 '19 at 17:25
  • Can you provide some HTML structure for your question? Also please format the question so as to include all code inside code blocks. It will help everyone to answer you quickly and better. – Divya Mamgai May 27 '19 at 17:29
  • Thanks for the response, I missed space, the HTML is full, everything else is done in jquery – Davit Mkrtchyan May 27 '19 at 17:53

1 Answers1

0

So the main problem was each function, it worked wrong because I did not reset that.top at the begging. So the correct way is this

var that= this;
that.prevAll = $(this).prevAll();
that.top = 0;

that.prevAll.each(function(){
  if(that.prevAll.hasClass('.column' + that.current_column)) {
   that.top += that.prevAll.height() + that.settings.imegesGap;
  }; 
enter code here
Davit Mkrtchyan
  • 449
  • 5
  • 15