Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap all HTML elements in a DIV depending on total height of those HTML elements using jQuery?

I am working on a functionality where I want to show elements in a div of height 1000px. There are multiple records coming from DB but height of each element is not fixed. When height of records displayed cross 1000px, they should be wrapped in one DIV. Next records should be wrapped in another DIV till the height of those elements total to 1000px. Record should not get broken in between because of separate DIVs.

For example:

<div class="record">..</div>
<div class="record">.....</div>
<div class="record">...</div>
<div class="record">....</div>
<div class="record">..</div>

If total height of first 3 .record totals to 940px & height of first 4 .record totals to 1100px, jQuery should convert the code to:

<div class="page>
    <div class="record">..</div>
    <div class="record">.....</div>
    <div class="record">...</div>
</div>
<div class="page>
    <div class="record">....</div>
    <div class="record">..</div>
</div>

I am spending lot of time on it but could not make it work. :(

like image 765
Nilesh G Avatar asked Feb 28 '16 07:02

Nilesh G


1 Answers

Take a look into this jsfiddle

But to explain it in details:

Some declarations:

var $records = $('.record'), // get all records
    total = 0, // current height of all elements
    group = 0, // iterator for groups
    limit = 200; // your limit in px for each .page (put your 1000 here)

First loop:

$records.each(function() {
    var $record = $(this);

    total += $record.outerHeight(true); // sum height of all records

    // when total height overflow your limit 
    // reset total and set next group index
    if (total > limit) {
        total = $record.outerHeight(true);
        group++;
    }

    // assign group index to each record
    $record.attr('data-group', group);
});

And second loop:

// iterate on all groups and using jQuery .wrappAll()
// wrap all records from one group to .page element
for (var i = 0; i <= group; i++) {
    $('[data-group="' + i + '"]').wrapAll('<div class="page"></div>')
}

More about jQuery .wrappAll()

Look out for .outerHeight(true) and all CSS margins/paddings/borders etc, because in this solution they will be counted in into example (I don't know if it's ok for You)

like image 113
Michał Kutra Avatar answered Oct 21 '22 00:10

Michał Kutra