Calculate space between Div and Body

2

I want to know the space between the bottom of Div A and the bottom of Body. I read about $.offset() , but this always returns me 0.

PS: I want only in relation to what appears on the screen. If the body is larger than the screen, I want it to be calculated only in relation to what appears on the screen.

PS2: Div A can be anywhere on the screen

    
asked by anonymous 18.05.2017 / 14:33

1 answer

3

If div is positioned at the top of body the calculation to find this distance is height of body minus height of div , so if div is elsewhere as in The image you presented in the question, the calculation will be, the height of the body minus the height of the div plus the distance that it is of the top of the body that can be easily obtained through the offset().top , the result will be the distance between the bottom of div and bottom of body .

* Note that the value is broken because of the border in both elements.

$(document).ready(function() {
  var alturaBody = $("body").height();
  var alturaDiv = $("#divA").height();
  var offsetTop = $("#divA").offset().top;
  console.log("Altura do body: "+alturaBody);
  console.log("Altura da div: "+alturaDiv);
  var espacoEntre = alturaBody - (alturaDiv + offsetTop);
  console.log("Dist. entre div e body: "+espacoEntre);
});
body {
  border: 1px solid red;
  height: 500px;
}

#divA {
  border: 1px solid black;
  height: 100px;
  margin-top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><body><divid="divA">
<div>
<body>
    
18.05.2017 / 14:54