Forum Moderators: open

Message Too Old, No Replies

Output Javascript variable(s) values to write CSS

Sounds harder than it is, I think.

         

Br3nn4n

10:53 am on Dec 15, 2009 (gmt 0)

10+ Year Member



I have a script that gets the size of the browser viewport and stores the height and width in variables named "viewportheight" and "viewportwidth" respectively.

I need to then use those values in some CSS (on the same page). So...how can I do this?

Thanks in advance!

rocknbil

6:00 pm on Dec 15, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A better idea might be to alter the attributes on load. For example (not working code, just to give you an idea:)

Edit: Curiosity got the better of me, here is some working code. Watch how the style is set to 500px, and note you must use a unit (px) to properly set it.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- doctype on one line -->
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Untitled</title>
<style type="text/css">
#container { width: 1000px; margin:auto; border:1px solid #000000; }
</style>
<script type="text/javascript">
window.onload=function() { adjustContainer(); };
function adjustContainer() {
// Here get your viewport values - let's say
// it determines the viewport is 800px, store it
// in var "width"
width=500;
if (width > 0) {
width += 'px';
document.getElementById('container').style.width=width;
}
}
</script>
</head>
<body>
<div id="container"><p>This is your content</p></div>
</body>
</html>

[edited by: rocknbil at 6:07 pm (utc) on Dec. 15, 2009]

chasehx

6:04 pm on Dec 15, 2009 (gmt 0)

10+ Year Member



Using Javascript you can can style properties of element in the page using the DOM. For example..

<div id="section">
i am content
</div>

could be accessed like this:
document.getElementById("section").style.[propertyname] = [propertyval];

You can find how to access each style property from the DOM by looking at the w3schools CSS reference pages. Each style property has is on method to be accessed through JavaScript.

edit: haha beating to the punch