How can I get the distance between two elements (midpoint)?

I need your help! I have a random number of sections arranged between each other.

<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 them has a different height, and I have to calculate the distance between them. It is very important that the distance from each midpoint of each element.

Thanks in advance!

Maybe my image will explain it better than my terrible English :) enter image description here

+3
jquery math
Aug 26 2018-12-12T00:
source share
4 answers

Oh my gosh! Sometimes it's easier than you think!

 var currentCenterPoint = $('.current').outerHeight() / 2; var nextCenterPoint = $('.current').next().outerHeight() / 2; var amount = (currentCenterPoint + nextCenterPoint); 
+1
Aug 26 '12 at 19:24
source share

You can try the 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) ; 
+3
Aug 26 '12 at 19:10
source share

Instead of <div> try <ul> with <li> .

0
Aug 26 '12 at 19:22
source share

jsBin demo

 $('.item').each(function(){ if( $(this).next().is('.item') ){ var myHalf = $(this).outerHeight(true)/2; var nextHalf = $(this).next('.item').outerHeight(true)/2; $(this).text('distance in between: '+ (myHalf+nextHalf) ); // TEST } }); 
0
Aug 26 '12 at 19:31
source share



All Articles