articles » current » javascript » browser-window-utility

JavaScript: Browser Window Utility

Find the true browser window size even if it has a scrollbar displayed

These functions return the browser's window dimensions/offset/center. windowCenter() returns an object with the x and y coordinants to use to center an absolutely positioned HTML element. The withScrollBar argument will return the window size excluding the width of the scrollbar.

// window.js
function windowOffset(){
	var offX = 0;
	var offY = 0;
	if(typeof window.pageXOffset != "undefined"){
		offX = window.pageXOffset;
		offY = window.pageYOffset;
	}
	else{
		if(document.documentElement.scrollTop == 0){
			offX = document.body.scrollLeft;
			offY = document.body.scrollTop;
		}
		else{
			offX = document.documentElement.scrollLeft;
			offY = document.documentElement.scrollTop;
		}
	}
	return{x:offX,y:offY};
}
function windowSize(withoutScrollBar) {
	var wid = 0;
	var hei = 0;
	if (typeof window.innerWidth != "undefined") {
		wid = window.innerWidth;
		hei = window.innerHeight;
	}
	else {
		if (document.documentElement.clientWidth == 0) {
			wid = document.body.clientWidth;
			hei = document.body.clientHeight;
		}
		else {
			wid = document.documentElement.clientWidth;
			hei = document.documentElement.clientHeight;
		}
	}
	return { width: wid - (withoutScrollBar ? (wid - document.body.offsetWidth + 1) : 0), height: hei };
}
function windowCenter(object){
	var object_width = parseInt(object.style.width);
	var object_height = parseInt(object.style.height); 
	var off = windowOffset();
	var siz = windowSize(true);
	return{x:parseInt(((siz.width-object_width)/2)+off.x),y:parseInt(((siz.height-object_height)/2)+off.y)};
}

Example usage:

<html>
	<head><title></title>
<script type="text/javascript" src="window.js"></script>
<script type="text/javascript">
	window.onload = function () {
		var obj = document.getElementById("divToPosition");
		var center = windowCenter(obj);
		obj.style.left = center.x + "px";
		obj.style.top = center.y + "px";
	};
</script>
	</head>
<body>
	<div id="divToPosition" style="position:absolute;width:100px;height:100px;background:#f00;"></div>
</body>
</html>

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE