Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the distance between 2 elements (middle point)?

Tags:

jquery

math

i need your help! I have a random amount of divs placed between themselves.

<div id="items">
    <div class="item">Item description</div>
    <div class="item">Item description</div>
    <div class="item">Item description</div>
    <div class="item">Item description</div>
</div>

Each of the has a different height and i have to calculate the distance between them. It is really important that the distance is from each middle point of each item.

Thanks in advance!

Maybe my image will it explain better than my horrible english :) enter image description here

like image 269
YeppThat'sMe Avatar asked Jan 30 '26 15:01

YeppThat'sMe


2 Answers

You can try offset method:

var $items = $('.item');
var fh = $items.eq(0).height();
var sh = $items.eq(1).height();
var first = $items.eq(0).offset().top + fh;
var two = $items.eq(1).offset().top;

var distance  = (two - first) + (fh/2) + (sh/2) ;
like image 119
undefined Avatar answered Feb 01 '26 09:02

undefined


Oh my gosh! Sometimes it is easier than you might think!

var currentCenterPoint = $('.current').outerHeight() / 2;
var nextCenterPoint = $('.current').next().outerHeight() / 2;

var amount = (currentCenterPoint + nextCenterPoint);
like image 26
YeppThat'sMe Avatar answered Feb 01 '26 09:02

YeppThat'sMe



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!