1
Alignment criteria:
- Align left from element with lower value of 'left'.
- Collision elements shall remain adjacent to the impacted element.
In the example the algorithm searches for the leftmost element in reference to the other elements and stores its position, then seeks 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’s going to collide or not? To know this the algorithm checks if the element that will align to the 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 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 the div1 is not colliding with the div3, as can be seen in https://fiddle.jshell.net/43jwxh35/ as when also two elements have the same position generates an alignment bug, could someone tell me what is wrong? Thanks
I confess that I am also not getting around the problem rsrs. You accept a new code?
– Samir Braga