Alignment criteria:
- Align left from element with lower value of 'left'.
- Elements with collision must remain beside the collided element.
In the example the algorithm searches the leftmost element in reference to the other elements and stores its position, then searches to align all other elements from the stored data.
arrayTopValue = [];
arrayLeftValue = [];
arrayLeftOriginal = [];
arrayWidth = [];
arrayHeight = [];
arrayIdDivs = [];
arrayAboutDivCollision = [];
$("#boxExample").children().each(function() {
//top
var position = $(this).css("top").indexOf("px");
var res = $(this).css("top").substr(0, position);
arrayTopValue.push(parseInt(res));
//left
var position = $(this).css("left").indexOf("px");
var res = $(this).css("left").substr(0, position);
arrayLeftValue.push(parseInt(res));
arrayLeftOriginal.push(parseInt(res));
arrayLeftValue.sort(function(a, b) {
return a - b
});
//width
var position = $(this).css("width").indexOf("px");
var res = $(this).css("width").substr(0, position);
arrayWidth.push(parseInt(res));
//height
var position = $(this).css("height").indexOf("px");
var res = $(this).css("height").substr(0, position);
arrayHeight.push(parseInt(res));
//idDivs
var tempIds = $(this).attr("id");
arrayIdDivs.push(tempIds);
});
How does the algorithm know it will collide or not? To know this the algorithm checks if the element that will align left, is above the stored element:
if (distTopPlusHeightRefNext < distTopRef)
{
$("#" + arrayIdDivsFolllow[i]).css({'left': arrayLeftValue[0] + "px"
});
If the element is above, it applies the stored left position to the element that will be left aligned.
The same thing happens if the element to be aligned is below the stored element.
if (distTopRefNext > distTopPlusHeightRef)
{
$("#" + arrayIdDivsFolllow[i]).css({'left': arrayLeftValue[0] + "px"
});
So when these two previous options are not possible to align, it means that the element will collide.
if (distTopPlusHeightRefNext > distTopRef && distTopRefNext < distTopPlusHeightRef) {
var tempValue = marginLeftPlusWidthRef;
tempValue = tempValue + 3; //Espaço entre os elementos em pixel
$("#" + arrayIdDivsFolllow[i]).css({'left': tempValue + "px"
});
Once the element collides, the reference values need to be updated so that the element can align from the nearest element. Ex: getValDivs ().
But there is an error because div1 is not colliding with div3, as can be seen in link as when two elements have the same position generates an alignment bug, could someone tell me what is wrong? Thankful