Javascript+CSS: calculate a height value on resize
I couldn't get my CSS to make a scrollable area correct, for a website i'm working now.
Normally, you can, with a little css, tell the browser to display a scrollbar for content that goes beyond its container's limits.
for instance, "overflow:auto". Yet for this to work, you need to give that container a 'height' value. But since my layout stretches on the entire height of the browser's viewport, that height value cannot be fixed... unless you'd use a little javascript that calculates the available height and writes the calculated value.
Anyway, i found that most of what i wanted was already done at the famous infamous quirksmode website, so i adapted to suit my needs.
here is the main function : (i dumped it in an external .js script called "viewport.js")
-
<!-- gives viewport dimension according tu user screen -->
-
// THIS FUNCTION RESIZES
-
// THE VIEWPORT SO THAT
-
// THE FULLPAGE IS USED,
-
// AND THE CONTENT IS SCROLLABLE
-
// WITH HEADER FOOTERS DISPLAYED AT ALL TIME
-
-
function sizeViewport(myObj,mySize) {
-
myObject = document.getElementById(myObj);
-
// THIS BIT DETECTS THE AVAILABLE SCREEN SPACE
-
// IT ORIGINATES FROM http://www.quirksmode.org/viewport/compatibility.html
-
-
var x,y;
-
if (self.innerHeight) // all except Explorer {
-
x = self.innerWidth;
-
y = self.innerHeight;
-
}
-
else if (document.documentElement && document.documentElement.clientHeight)
-
// Explorer 6 Strict Mode
-
{
-
x = document.documentElement.clientWidth;
-
y = document.documentElement.clientHeight;
-
} else if (document.body)
-
// other Explorers
-
{
-
x = document.body.clientWidth;
-
y = document.body.clientHeight;
-
}
-
// THIS IS THE ACTUAL RESIZING OF THE VIEWPORT
-
viewportHeight = y - mySize;
-
myObject.style.height = viewportHeight + "px";
-
return 'resized';
-
}
Secondly, you call your external .js file inside your html page:
Lastly, you just call the function, indicating the div to receive the height value, make sure you replace the '300' value by the one you need
-
function onResizeHandler() {
-
// ALL FUNCTION CALLS TO PERFORM ON RESIZE...
-
sizeViewport('viewport','300');
-
}
-
function onLoadHandler() {
-
// ALL FUNCTION CALLS TO PERFORM ON LOAD...
-
sizeViewport('viewport','300');
-
}
-
window.onresize = onResizeHandler;
-
window.onload = onLoadHandler;
it's working almost ok: the only case in which it screwes up, is if you use "doubleclicking" the browser title bar to expand/minimize the window, the script does not act, as there aren't any "onDoubleclickBrowserTitlebar" event in Javascript yet.
All the best,
Alex
Author: pixeline
Date: October 4th, 2005
filed in: Development
Follow the discussion on this entry via RSS 2.0 feed.