DHTML/Dynamic Width based on Browser Window
Expert: Andrew Hoffman - 1/2/2009
QuestionI have a site that has a top and left static navigation pane. Using JavaScript, I've been able to determine the width and height of the browser client window and to adjust those values to account for the navigation panes. However, when it comes to defining the data region's width and height in a div, I cannot seem to figure out how to get the JavaScript values into the div element. Help!
The div in question looks like this:
<div id="data" style="position: absolute; top: 54px; left: 186px; z-index: -1; width: 940px; height: 775px; overflow: auto;">
Where "width" and "height" are temporary hard-coded values that need to be dynamic, based on what's leftover from a visitor's browsing session (based on their preferred sizing for their browser).
The JavaScript used to get the client window sizes is:
function getClientWidth() {
return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}
function getClientHeight() {
return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}
... and the calculated available space is a simple math calculation (remove 187 from width and 54 from height). What do I do to put dynamic width and height values into the div?
Thanks in advance.
AnswerHi Kehvan,
You probably forgot to add "px" after the desired height or width value. Without it, the dimensions of the div won't change. Run the simple example below to see what I'm talking about.
Andrew
--
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title></title>
<script type="text/javascript">
function changeDimensions() {
document.getElementById("data").style.height = 300 + "px";
document.getElementById("data").style.width = 400 + "px";
}
</script>
</head>
<body>
<div id="data" style="position: absolute; top: 54px; left: 186px; z-index: -1; width: 940px; height: 775px; overflow: auto; border: 1px solid black;">Here is my div. Click that link and change my height.</div>
<a href="#" onclick="changeDimensions()">Change dimensions of div</a>
</body>
</html>