Jump to content

Using Javascript To Write A <div> Tag


Matteo
 Share

Recommended Posts

I am experimenting with various ways to re-size a <div> tag based on the size of the browser window.I have come up with a script that writes the actual <div> tag in the HTML, but does HTML parse after the Javascript? If not, then no matter how I get the syntax, it won't populate correctly because the HTML will not see the Javascript until too late.Here is the code...

<body>	<script type="text/javascript">		document.write('<div id=\'container\' style=\"top: ' +top+ '\"; \"left: ' +left+ '\"; \"right: ' +right+ '\"; \"bottom: ' +bottom+ '\";')	</script>	</div> <!-- End CONTAINER div -->

Any help?

Link to comment
Share on other sites

First of all, you cannot use top, left, right, or bottom of the box does not have relative, absolute or fixed as the CSS position.If you just want a box that resizes with the window, you don't need Javascript. This should do it:

html,body {  margin: 0;  padding: 0;  height: 100%;}#box {  position: absolute;  top: 10%;  left: 10%;  width: 80%;  height: 80%;}

I am using a box of this kind in one of the sites I'm building at the moment.You can apply a min-height and max-height as well.

Edited by Ingolme
Link to comment
Share on other sites

First of all, you cannot use top, left, right, or bottom of the box does not have relative, absolute or fixed as the CSS position.If you just want a box that resizes with the window, you don't need Javascript. This should do it:
html,body {  margin: 0;  padding: 0;  height: 100%;}#box {  position: absolute;  top: 10%;  left: 10%;  width: 80%;  height: 80%;}

I am using a box of this kind in one of the sites I'm building at the moment.You can apply a min-height and max-height as well.

This will work if you are just sizing one element, but I have custom elements that I need to place specifically, yet fluid (liquid) depending on the user's browser, their screen resolution, whether they resize the browser, etc. I can't use percentage tags because the ratios don't always work on liquid layouts.
Link to comment
Share on other sites

First of all, you cannot use top, left, right, or bottom of the box does not have relative, absolute or fixed as the CSS position.If you just want a box that resizes with the window, you don't need Javascript. This should do it:
html,body {  margin: 0;  padding: 0;  height: 100%;}#box {  position: absolute;  top: 10%;  left: 10%;  width: 80%;  height: 80%;}

I am using a box of this kind in one of the sites I'm building at the moment.You can apply a min-height and max-height as well.

You are right, I just left off the position: x statement for brevity. Can you give me an example of using Javascript to write a <div> tag? I can't seem to get it to work.
Link to comment
Share on other sites

You're missing the point - don't write the div tag with Javascript. Only use Javascript to update the size of the existing element once the page loads.If you want to add an element to a page, you should use document.createElement and then the appendChild method on the parent container that you want the new element to go into. But it's going to be more flexible to only use Javascript to resize existing elements versus creating them.

Link to comment
Share on other sites

Can you think of a way to do it, though? Write the <div> tag with Javascript?
There is nothing technically wrong with your original method of writing a div tag. This is how people include 3rd-party ads, for instance. They put a script where the ad should be, and the script uses document.write() to write out the element. If you're routine wasn't working, maybe there's a bad quotation mark or something.But it's a technique of last resort, useful for 3rd-party stuff because it needs to be self-contained. The advice you've been given is good.To clarify: write the div in your original HTML. To your CSS, add all the style stuff for that div that won't get changed. Maybe include default values also. Add a window.onload handler to your main javascript. It should adjust the style features like this:var el = document.getElementById("container");el.style.height = some_value;
Link to comment
Share on other sites

There is nothing technically wrong with your original method of writing a div tag.
The only thing that's a little strange with that is that he was using Javascript to only write the opening tag, not the content or the closing tag. I'm not sure how the browser would handle that, but it might work.
Link to comment
Share on other sites

The only thing that's a little strange with that is that he was using Javascript to only write the opening tag, not the content or the closing tag. I'm not sure how the browser would handle that, but it might work.
I understand that this is an unconventional request; thanks for your input. In case your were wondering, the writing of the first <div> in JS and leaving the static HTML </div> works. Here's the code I came up with. My only hurdle is trying to get the style elements to take variables as inputs.<body> <script type="text/javascript"> <!-- Begin CONTAINER div document.write('<div id=\"container\" style=\"position: absolute;top: 10px;left: 200px;right: 500px;bottom: 350px\">'); document.write('<p>This is the Container div (Inline)...</p>'); //For testing purposes... //--> </script> </div> <!-- End CONTAINER div --></body>My whole purpose in asking all this is I need to (attempt) make semi-liquid layout for a client. The have a centered container div, with a static header, footer, left sidebar, right sidebar, and content. All the elements remain the same height, regardless of the browser size or the screen resolution. The only div that should be truly liquid is the content area. The challenge is in getting the style.overflow = auto to work properly in the content div. If the content extends beyond the top of the footer, it pushes the footer down, ruining the client's desired layout. Just FYI.
Link to comment
Share on other sites

In order to get overflow: auto to work properly, the element needs to have a defined height.I'm not sure what other requirements your page has. Is it allowed to extend beyond the bottom of the window? is it supposed to take the full width of the window?Here's a layout that has the following properties:

  • header, footer, left and right column never change width nor hight; no matter what resolution or window size.
  • The content <div> shows a scrollbar as long as content gets outside of it.
  • The whole site is centered vertically and horizontally

<div id="wrapper"><div id="header">Header</div><div id="left">Left column</div><div id="right">Right columnr</div><div id="content">Content</div><div id="footer">Footer</div></div>

/* Color coded */#header,#footer { background-color: blue; }#left,#right { background-color: green;}#content { background-color: white; }/* CSS for layout */#wrapper {  position: absolute;  width: 800px;  height: 600px;  left: 50%;  right: 50%;  margin-left: -400px;  margin-top: -300px;}#header,#footer { height: 120px; }#footer { clear: both; }#left,#right { width: 120px; }#content {  margin: 0 120px;  height: 360px;  overflow: auto;}

Edited by Ingolme
Link to comment
Share on other sites

Your original plan was on the right track, but the quote marks were all messed up -- most of the double quotes were unnecessary. I see you've noticed the missing bracket, which was also wrong in the original. The following works:var top="50px";var left="50px";var width="50px";var height="50px";document.write('<div id="container" style="position: absolute; top: ' +top+ '; left: ' +left+ '; width: ' +width+ '; height: ' +height+ '">')I switched out right and bottom because they sometimes fool older browsers. width and height ALWAYS work. I assume you can generate values for them, since I assume you're generating values for right and bottom.

Link to comment
Share on other sites

There is nothing technically wrong with your original method of writing a div tag. This is how people include 3rd-party ads, for instance. They put a script where the ad should be, and the script uses document.write() to write out the element. If you're routine wasn't working, maybe there's a bad quotation mark or something.But it's a technique of last resort, useful for 3rd-party stuff because it needs to be self-contained. The advice you've been given is good.To clarify: write the div in your original HTML. To your CSS, add all the style stuff for that div that won't get changed. Maybe include default values also. Add a window.onload handler to your main javascript. It should adjust the style features like this:var el = document.getElementById("container");el.style.height = some_value;
I can't seem to get that to work. I have moved (for testing purposes) all var to global scope. This is the code that I have...//GLOBAL VARIABLESvar elContainer = document.getElementById('container');var cTop = "10px";var cLeft = getSize().scrnWidth/2 - 512; //ASSUME THESE FUNCTIONS WORK, THEY DO...var cRight = getSize().scrnWidth/2 + 512;var cBottom = getSize().scrnHeight - 10;function drawContainer() {document.write('accessed the drawContainer function...'); elContainer.style.top = cTop; elContainer.style.left = cLeft; elContainer.style.right = cRight; elContainer.style.bottom = cBottom; }drawContainer;Inside my HTML I have the following...<div id="container"> </div><!-- End CONTAINER div -->I don't know if it's an issue of scope or what, but I can't get document.getElementById('container') to work... Can you find something wrong with my approach?
Link to comment
Share on other sites

I'd have to see the whole document to be sure. A common problem is trying to access page elements before they are drawn. So if drawContainer() is called before the HTML for 'container' is loaded, then 'container' won't be found.Odd then that you can find it in the global space, because that usually gets loaded BEFORE the page elements get loaded. Unless that part of your script is literally below the page element?So that's why I can't be sure. I don't know how the pieces fit together.What's this line supposed to do?drawContainer;Without the parentheses it's not a function call. It's not an assignment. It's just sitting there.If you're using a strict doctype, better append "px" to your style assignments. E.g.:elContainer.style.top = cTop + "px";

Link to comment
Share on other sites

I'd have to see the whole document to be sure. A common problem is trying to access page elements before they are drawn. So if drawContainer() is called before the HTML for 'container' is loaded, then 'container' won't be found.Odd then that you can find it in the global space, because that usually gets loaded BEFORE the page elements get loaded. Unless that part of your script is literally below the page element?So that's why I can't be sure. I don't know how the pieces fit together.
Ok, for clarity I have included the entire relevant JS and HTML code here. The HTML calls the JS from an external script...<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="distribution" content="global"/> <meta name="robots" content="follow, all"/> <meta name="language" content="en"/> <link href="styles/psIndex.css" rel="stylesheet" type="text/css"/> <script type='text/javascript' src='/js/extScript.js'></script> </head> <body> <div id="container" onload="drawContainer"> </div><!-- End CONTAINER div --> <script type="text/javascript"> drawPage(); </script> </body></html>and the JS file...//GLOBAL INDEPENDANT VARIABLES//var elContainer = document.getElementById('container');function getSize() {var h = window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight; var w = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth; return {scrnWidth : w , scrnHeight : h } } function drawContainer() { elContainer.style.top = cTop + 'px'; elContainer.style.left = cLeft + 'px'; elContainer.style.right = cRight + 'px'; elContainer.style.bottom = cBottom + 'px'; }function drawPage() { getSize(); drawContainer(); }if(window.addEventListener) {window.addEventListener('resize',drawPage,false); } else // For IE 6.0 and up {window.attachEvent('onresize', function() {drawPage(); }); }//GLOBAL DEPENDANT VARIABLESvar cTop = "10px";var cLeft = getSize().scrnWidth/2 - 512;var cRight = getSize().scrnWidth/2 + 512;var cBottom = getSize().scrnHeight - 10;drawPage();From your comment, it looks like I'm trying to call the function that draws the container div before the HTML has rendered the div, but I need it to dimension itself before the user sees the page loaded. As, shown in red in the code, I have tried calling the drawPage() function as the very last line of the <body> tag (and removed it from the JS code), but that didn't resolve it either.I hope that helps understand my logic. Any ideas?
Link to comment
Share on other sites

This could be condensed further, but it does what you want.As I suspected, without width and height definitions, the div might as well not exist, so I changed that. It might require changing the values, also. Ultimately, I think this was your biggest problem. I explicitly made the position absolute, because I wasn't sure if that was in your style sheet or not.It looks like you were thinking your initial assignments to cLeft and so on would stay dynamic (ie, calling getSize() every time they're accessed). Doesn't work that way. So I just redefine them in the getSize() function. This allows the resize event handler to work correctly.

cTop = 10;cLeft = 0;cRight = 0;cBottom = 0;function getSize(){	var h = window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight;	var w = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;	cLeft = w/2 - 512; // FWIW, this worked out to -2 on my browser	cRight = w/2 + 512;	cBottom = h - 10;}function drawContainer(){	var elContainer = document.getElementById('container');	elContainer.style.position = "absolute";	elContainer.style.top = cTop + 'px';	elContainer.style.left = cLeft + 'px';	elContainer.style.width = cRight + 'px';	elContainer.style.height = cBottom + 'px';}function drawPage()	{	getSize();	drawContainer();}if (window.addEventListener) {	window.addEventListener('resize',drawPage,false);} else {	window.attachEvent('onresize', function() {drawPage(); });}

Edited by Deirdre's Dad
Link to comment
Share on other sites

function drawContainer(){ var elContainer = document.getElementById('container'); elContainer.style.position = "absolute"; elContainer.style.top = cTop + 'px'; elContainer.style.left = cLeft + 'px'; elContainer.style.width = cRight + 'px'; elContainer.style.height = cBottom + 'px';}
I'm getting "elContainer not defined" or elContainer = Null (in firebug). I can't seem to correct the problem.
Link to comment
Share on other sites

Is drawContainer() still called by drawPage(), and does your HTML look like this?<body> <div id="container"><!-- div elements don't have load events --> </div><!-- End CONTAINER div --> <script type="text/javascript"> drawPage(); </script> </body>And that's the first time drawPage() is called, in the script that follows the div?

Link to comment
Share on other sites

Is drawContainer() still called by drawPage(), and does your HTML look like this?<body> <div id="container"><!-- div elements don't have load events --> </div><!-- End CONTAINER div --> <script type="text/javascript"> drawPage(); </script> </body>And that's the first time drawPage() is called, in the script that follows the div?
#1. Yes, drawContainer() is called by drawPage().#2 Yes. HTML does not contain onLoad event triggers in the <div> tag.I am calling the drawPage() after the close of the </body> tag, but before the </html> tag.
Link to comment
Share on other sites

I am calling the drawPage() after the close of the </body> tag
Hmm. No document elements can technically exist there. I don't know if it's the problem, though. You can put a script BEFORE you close the body. Might as well change it, since doing so will correct the syntax. If it doesn't solve the problem, better post the whole darned thing.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...