Reputation: 371
I need to find the distance between the element and the bottom of the browser window.
When I select the element, and the distance between the element and the bottom of the browser window is smaller than 50px, I want to make the window scroll automatically.
Any ideas? I'd prefer to use jQuery.
Upvotes: 35
Views: 62323
Reputation: 1757
Using element.getBoundingClientRect()
is a nice straight forward way to get the offset of the bottom of the element which is relative to the viewport rather than the document. Then you can just subtract this value from window.innerHeight
to calculate the remaining space between the element and the bottom of the browser window (viewport). Like in the example below:
var element = document.querySelector('.inner');
window.onscroll = function() {
var domRect = element.getBoundingClientRect();
var spaceBelow = window.innerHeight - domRect.bottom;
element.style.background = (spaceBelow < 50 ? 'blue' : 'transparent');
};
body {
height: 1000px;
}
.outer {
position: absolute;
top: 120px;
border: 1px dashed green;
width: 95%;
height: 80px;
}
.inner {
width:300px;
height:16.2%;
position: absolute;
top: 48.11%;
border:3px dotted black;
}
<div class="outer">
<div class="inner"></div>
</div>
If you prefer to use jQuery then alternatively the following code should also work:
var spaceBelow = $(window).height() - $('.inner')[0].getBoundingClientRect().bottom;
Upvotes: 23
Reputation: 65785
Unlike other systems coordinates in browser is from top to bottom, it means top of the browser is y=0.
There is two DOM element property for getting position of an element on the page. The properties are element.offsetTop
and element.offsetHeight
You can calculate the space between your element and bottom of the page by calculating element.offsetTop
and window.innerHeight
.
var space = window.innerHeight - element.offsetTop
if you want to calculate space between bottom of your element and bottom of the window then you need to add your element height too.
var space = window.innerHeight - element.offsetTop + element.offsetHeight
This calculation is sometimes necessary. Think you have percent based positioning and you want to know position of your element by pixels to do something. For example you have a div positioned like this:
div{
width:300px;
height:16.2%;
position:absolute;
top: 48.11%;
border:3px dotted black;
}
Then you want to know when the div is close to browser window to change it's color:
var div = document.querySelector('div'),
space = innerHeight - div.offsetTop + div.offsetHeight;
window.onresize = function(){
space = innerHeight - div.offsetTop + div.offsetHeight;
if(space < 200){
div.style.background = 'blue';
}
};
Upvotes: 36