YeppThat'sMe
YeppThat'sMe

Reputation: 1862

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

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

Upvotes: 3

Views: 8211

Answers (4)

YeppThat&#39;sMe
YeppThat&#39;sMe

Reputation: 1862

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);

Upvotes: 2

Roko C. Buljan
Roko C. Buljan

Reputation: 206151

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  
  }
                  
});  

Upvotes: 0

Ramprasad
Ramprasad

Reputation: 8071

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

Upvotes: 0

Ram
Ram

Reputation: 144689

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) ;

Upvotes: 3

Related Questions