How (using either jQuery, or JavaScript...)
<div style="background-color:red;height:10px;width:10px;float:left;"></div>
<div style="background-color:red;height:10px;width:10px;float:left;margin-left:25px;"></div>
<br>
<div style="background-color:red;height:10px;width:10px;margin-left:15px;" id="2">
Do I get what element is closest to id=2? I need this type of selector, and any help would be appreciated. :)
Note that I don't mind setting a position:relative or absolute and left:(number)px to these elements.
I need a code that would work in a dynamic environment; you know, when blocks keep getting created and keep scrolling forwards and changing left position. Could I use .position() perhaps? Somehow?
Thank you. :)
That's a fun thought experiment...
To solve this, you'd probably want to calculate the offset of each element, and compare those coordinates (top and left) to other elements.
Assuming you want to find the element closest to compareEl, and you have compareElTop and compareElTop, loop through all elements on screen (except compareEl), and do something like this:
var topDiff = Math.abs(compareElTop-elements[x].offset().top);
leftDiff = Math.abs(compareElLeft-elements[x].offet.left);
Pair with the lowest topDiff+leftDiff is closest.
Here is a nice jsFiddle for you to play around with! All kinds of awesome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With