Reputation: 13
Hey guys I have an absolute position for an element that will be created in the future. I want to check if the element is going to be entirely visible on the current viewport. I know I could use getBoundingClientRect
if the element was rendered on the page, however it's not and it couldn't not be. Is there a way that I can detect if given absolute coordinates (left, top, bottom, right) are going to be visible on the current viewport? Thanks in advance.
Edit:
My solution so far - insert an element with visibility: hidden
and use getBoundingClientRect
, I was just wondering if there is a better way.
Upvotes: 0
Views: 1211
Reputation: 26696
If you have the absolute coordinates of this unrendered element (ie: you can pull them from JS variables, or read them from somewhere, or hard-code them or even write a script to read them out of a <style>
tag on the page...), then you can do something like this:
var viewport = {
x : 0,
y : 0,
width : 0,
height : 0,
update : function () {
this.x = document.body.scrollLeft || document.documentElement.scrollLeft;
this.y = document.body.scrollTop || document.documentElement.scrollTop;
this.width = document.documentElement.clientWidth;
this.height = document.documentElement.clientHeight;
}
};
Now you should be able to check for intersections between your element's x,y,width,height against the viewport's x,y,width,height.
Any time the user scrolls, just hit viewport.update();
.
I will say this:
This method should be fairly cross-browser compatible, but I really can't make any guarantees in terms of IE6 -- especially in Quirksmode (no <!doctype>
on the html file).
Upvotes: 1
Reputation: 7314
Check this out: https://stackoverflow.com/a/1823700/1060487
function alertSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );
}
Upvotes: 0
Reputation: 26940
Check screen.height and screen.width and compare it to dimensions of the element
Upvotes: 0