Reputation: 79309
Suppose I've the following HTML page:
<body>
<div id="top" style="height: 100px"></div>
</div>
How do I find what the height of the page below the div#top
is and assign it to a variable in JavaScript (jQuery is allowed)?
What I mean is the following:
<body>
.-------------------------------. ^
| <div id="top">...</div> | | 100 px
|-------------------------------| v
| ^ | ^
| | | |
| How do I find | | | rest of the page
| this height: | | | (nothing here, it's empty)
| | | |
| | | |
| | | |
| | | |
| v | v
'-------------------------------'
</body>
For example, if the visible part of browser window height is 1000px, then I'm looking for answer 900px. If the window height is 777px, then I'm looking for answer 677px. Etc.
Upvotes: 1
Views: 2874
Reputation: 12027
I think the code is self-explanatory. Here's a fiddle. Resize the frame height to see the change in height.
var topElement = document.getElementById("top");
var topElementHeight = parseInt(getComputedStyle(topElement).height, 10);
var windowHeight = window.innerHeight;
var bodyMargin = parseInt(getComputedStyle(document.body).margin, 10);
var availableHeight = windowHeight - topElementHeight - bodyMargin;
topElement.innerText = availableHeight;
#top {
height: 100px;
background: red;
}
<div id="top"></div>
Upvotes: 0
Reputation: 240878
You can't dynamically find the height in CSS, but you can use calc()
to calculate the remaining height.
In this case, height: calc(100% - 100px)
would work.
You can also use viewport-relative units - height: calc(100vh - 100px)
.
If you want to dynamically find the amount of space below an element, just subtract the height of the viewport from the position of the bottom of the element.
Pure JavaScript: (example)
var element = document.querySelector('#target'),
remainingHeight = document.documentElement.clientHeight - element.getBoundingClientRect().bottom;
alert(remainingHeight); // Height below element
Equivalent version with increased readability:
var element = document.querySelector('#target'),
elementBottom = element.getBoundingClientRect().bottom,
viewportHeight = document.documentElement.clientHeight,
remainingHeight = viewportHeight - elementBottom;
alert(remainingHeight); // Height below element
jQuery alternative: (example)
var $element = $('#target'),
remainingHeight = $(window).height() - ($element.position().top + $element.outerHeight(true));
alert(remainingHeight); // Height below element
Equivalent version with increased readability:
var $element = $('#target'),
elementBottom = $element.position().top + $element.outerHeight(true),
viewportHeight = $(window).height(),
remainingHeight = viewportHeight - elementBottom;
alert(remainingHeight); // Height below element
Just take the box-model into consideration with both of these solutions, and adjust accordingly. The JavaScript method above doesn't take the element's margin into consideration; whereas the jQuery solution does. You haven't made it clear which you want.
Upvotes: 2