Reputation: 2519
How to define a position (co-ordinates of left top corner) of an element relatively a browser window, instead of the document?
Crossbrowser compatible, pure javascript.
Upvotes: 0
Views: 992
Reputation: 536379
I'm guessing you're talking about ‘fixed position’ elements, that stay in the same place on the window as you scroll it?
This can be done with plain CSS, and should be because it'll be smoother to let the browser do it than you can manage with JavaScript. You only need JS backup if you need the element to stay fixed on IE6, which doesn't support this; newer versions work with the CSS, as long as you are in Standards Mode (which you should be).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<style type="text/css">
#foo {
position: fixed;
left: 100px; top: 100px; width: 200px; height: 200px;
background: red;
}
</style>
</head>
<!--[if lt IE 7]><body class="browser=ie6"><![endif]-->
<!--[if gte IE 7]><!--><body><!--<![endif]-->
<div id="foo">Hello</div>
<script type="text/javascript">
if (document.body.className=='browser=ie6') {
// Simple fallback `position: fixed` support for IE6. Elements to be fixed
// must be positioned with `px` values for `left` and `top`.
//
function PositionFixer(element) {
var x= parseInt(foo.currentStyle.left, 10);
var y= parseInt(foo.currentStyle.top, 10);
function fixposition() {
foo.style.left= x+document.documentElement.scrollLeft+'px';
foo.style.top= y+document.documentElement.scrollTop+'px';
}
window.attachEvent('onscroll', fixposition);
fixposition();
foo.style.position= 'absolute';
}
PositionFixer(document.getElementById('foo'));
}
</script>
</body></html>
Upvotes: 2
Reputation: 11936
element position from browser window = (element position from document) - (amount document has scrolled)
Find an element's position relative to the document: http://www.quirksmode.org/js/findpos.html
Amount document has scrolled: http://www.quirksmode.org/dom/w3c_cssom.html#t35 (scrollLeft / scrollTop)
Upvotes: 1
Reputation: 449415
Can't be done AFAIK. The viewport of the current document is the only thing you can position things relatively to.
You can find out the screen's available space using the screen.availHeight
property but that won't give you the space between the browser's top left corner and the document's top left corner (which is what you would need).
Upvotes: 1