Calculate space between Div and Body

Asked

Viewed 1,062 times

2

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

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

PS²: Div A can be anywhere on the screen

inserir a descrição da imagem aqui

1 answer

3


If the div is positioned at the top of the body the calculation p/ find that distance is the height of the body minus the height of div, thus, if the div is in another place as in the image you presented in the question, the calculation will be, the height of the body minus the height of div plus the distance she’s from the top of the body which can easily be obtained through offset().top, the result will be the distance between the bottom of the div and below the body.

*Note that the value is broken because of the edge on 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>
<div id="divA">
<div>
<body>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.