On a series of div elements, I have implemented some JS/jQuery code that organizes them by wrapping every three elements in a container with the class .each-row
.
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
results in:
<div class="each-row">
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
</div>
<div class="each-row">
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
</div>
The JavaScript code used for this functionality is as follows:
// Grab all the .bricks
var brick = $('.container .brick');
// Iterate through all the .bricks
for (var i = 0; i < brick.length; i += 3) {
// Create container
var brickContainer = $('<div />', {
class: 'each-row'
});
// Wrap all the .bricks inside the container
brick.slice(i, i + 3).wrapAll(brickContainer);
}
This solution works effectively, however, I aim to incorporate breakpoints so that under different screen sizes, the elements are organized differently. When the screen size is 767px or below, each .brick
should be wrapped in an each-row
, and if it's less than 1224px, wrap every two bricks, otherwise wrap every three.
I have already achieved this through the use of the resize function and even provided a demonstration on JSFiddle. The only issue encountered is that due to resizing, the each-row
gets added at every pixel change. When inspecting the DOM during the resize process on JSfiddle, you'll notice the continuous addition of each-row
.
Any suggestions on how to resolve this would be greatly appreciated.
Thank you, R