Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery or JavaScript get element near other element

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. :)

like image 444
user3092778 Avatar asked Jun 13 '26 17:06

user3092778


1 Answers

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.

like image 62
Julian H. Lam Avatar answered Jun 15 '26 05:06

Julian H. Lam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!