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. :(
Take a look into this jsfiddle
But to explain it in details:
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)
$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);
});
// 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With