our client wants to add banner with some ads or links to other special pages to their product listing at their eshop. There are maximum 4 items per line (depends on resolution). Banners could be from 1 to 4 product-sizes big. So, when they are the size of 2 and places at 3rd place at row, at lower resolutions, there appear empty place (because there are 2 other items at row, and banner should be 2-size big, so it cant fit at the same row). So we have to switch this banner with next element to fill this gap.
We've created this function that foreach every element in "snippet", every element is div with product or banner + there are other calculations if there are empty space at the end or not. Function calls itself recursively when it swap some items, because there could be need to swap more items (bigger banners, more banners).
function orderBanners() {
$rowSize = document.getElementById('snippet--filteredproducts').offsetWidth;
$actualRowSize = 0;
$("#snippet--filteredproducts > div").each(function(){
$nextItem = $actualRowSize + this.offsetWidth;
if($nextItem == $rowSize) {
/* Jump to next row */
$actualRowSize = 0;
} else if($nextItem > $rowSize) {
/* Swap with next item */
/* TODO */
orderBanners();
return;
} else {
$actualRowSize += this.offsetWidth;
}
});
}
I have "this" selected, and I want to swap it with next element from this foreach, then there are return and recursive call. I've tried some things with insertBefore() function, but I don't know how to fit it.
You can store the current div(the one that needs to be moved) in a variable.
After storing it, remove it from the DOM, and the append it after the "targeted" div.
Some quick example:
const myDiv = $("#myDiv"); //in your case, that I think that will be $(this)
$("#myDiv").remove();
$nextItem.append(myDiv);
Try to fit this logic in your use case and I think that will work.