javascript – How to calculate divs next to each other?

Question:

There is a group of a certain number of divs, which are scattered randomly. Some of this group of divs are side by side (at the coordinates (left, top)). It is necessary to calculate the divs that are next to each other (by their coordinates).

div is generated each time a different number (always even), after the div is generated, the script for checking adjacent divs will be launched.

It is necessary to display, for example, to the console all the divas that are next to each other, in my example "block_2" and "block_4" as well as "block_1" and "block_3" stand next to each other. You should get something like "" block_2 and block_4, block_1 and block_3 are next to "

This is how I tried to implement it:

 var rects = {}; var checed_position = function(){//-- функция проверки на совпадения var t_left; //--- координаты елементов то левой стороны var t_top; //--- координаты елементов от верху var create_mass = function (){ $( ".rects" ).each(function(index, element) { rects[index] = element; t_left = $(element).offset().left; t_top = $(element).offset().top; console.log(t_top) }); $.each(rects, function(key, value) { if(t_top == $(value).offset().top){ if(t_left == $(value).offset().left + 88 || t_left == $(value).offset().left - 88){ // --- вычисляем есть ли совпадения с какойто из сторон alert("Есть совпадения"); console.log($(value)); } }else{ console.log("Нет совпадний"); console.log($(value).offset().left) } }); } create_mass(); } checed_position();
 #block_1,#block_2, #block_3, #block_4, #block_5{ width: 88px; height: 100px; margin: 50x; text-align: center; float: left; cursor: pointer; position: absolute; } #block_1 { background-color: #f443a1; left: 388px; top: 300px; } #block_2 { background-color: chartreuse; left: 500px; /* top: 200px; */ } #block_3 { background-color: aqua; left:300px; top: 300px; } #block_4 { background-color: #5b00ff; left: 588px; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="rects" id="block_1"> </div> <div class="rects" id="block_2"> </div> <div class="rects" id="block_3"> </div> <div class="rects" id="block_4"> </div>

In the example above, the function shows the collisions while outputting the current of one div, it should be 4.

Who did this before, tell me how to implement it?

Answer:

You have $.each(rects, fn) executed before the entire reacts object is created; Wrap it in a timeout for example:

setTimeout(function(){
    $.each(rects, fn);
}, 0) 
Scroll to Top