RetroCoder
RetroCoder

Reputation: 2685

Find height for a set of floating divs as if it were a single div

Given a selection of floating divs what is the height of only the set A-G as if the height of A-G were a single div?

Example positions depend on width of viewport Divs A thru G.

    <section>
        -->  [A][B][    C   ][D]
        |    [                 ]
        |    [                 ]
height--|    [        E        ] 
        |    [                 ]
        |    [                 ]
        |    [         F           ]
        -->  [G]
        ...
        [ Z ]
    </section>

So I guess there may be a trick to find only the left most divs with the same smallest left position and then retrieve the heights from each of those items. I want to select only a A - G height not A-Z height. Is there a more accurate or standard way to do this even if the left position doesn't match precisely?

var gatherHeight = 0;
var sectionLeft = $("section").position().left;
$("section > div:nth-child(-n+7)").each(function() {
  if ($(this).position().left == sectionLeft)
  {
     gatherHeight += $(this).height();
  }
});

Upvotes: 0

Views: 39

Answers (1)

Mitchell Layzell
Mitchell Layzell

Reputation: 3058

To my understand the way jQuery each fucntion works is you pass an array of elements that you want to loop through as a parameter like so,

jQuery

var height = 0;
var elements = $('.elements');

$.each(elements,function(key,value) {

   height += $(this).height();
});

Pure JS

var height = 0;

var elements = document.querySelectorAll('.elements');

for(var i = 0;i < elements.length;i++) {

    height += elements[i].offsetHeight();
}

UPDATE

HTML

<section>
    <div class="parent in-viewport">
        <div class="child">

        </div>
        <div class="child">

        </div>
        <div class="child">

        </div>
    </div>
    <div class="parent out-viewport">
        <div class="child">

        </div>
        <div class="child">

        </div>
        <div class="child">

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

jQuery

var height = 0;
var parents = $('.in-viewport');

$.each(parents,function(key,value) {

   height += $(this).height();
});

Upvotes: 1

Related Questions