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

I am working on functionality where I want to show elements in a div with a height of 1000 pixels. There are several records coming from the database, but the height of each element is not fixed. When the height of the displayed records crosses 1000 pixels, they should be wrapped in one DIV. The following entries should be wrapped in another DIV until the height of these elements is 1000px. Recording should not be interrupted between them due to separate divs.

For instance:

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

If the total height of the first 4.record is 940px and the height of the first 4.record is 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 spend a lot of time on this, but can't get it working. :(

+6
source share
1 answer

Take a look at this jsfiddle

But for a detailed explanation:

Some announcements:

 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 cycle:

 $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 the second cycle:

 // 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>') } 

Learn more about jQuery.wrappAll ()

Take a look at .outerHeight(true) and all CSS margins/paddings/borders , etc., because in this solution they will be taken into account in the example (I don't know if this is normal for you)

+3
source

All Articles