views:

709

answers:

3

I've an html page with varying size. Based on the conditions i hide some contents. How can i get the width and height of the body with javascript, so that i can resize the window size dynamically based on the amount of contents of the page. Thanks...

+1  A: 

Well, document.body.offsetWidth and document.body.offsetHeight should do the trick for you. Remember that setting the window size is going to be different from the viewport size, depending on whether you have statusbar, etc.

Oh, you are looking for the viewport size. Here is a link to a site that explains how to do that cross-browser.

Robusto
but that gives me the size of the maximized window. for me it gives 1280. I like to get the width and height of my window content. It changes between 200 to 300 normally.
coder247
Using the same idea, could you not wrap the page inside a named div or span, and get the size of that?
icabod
@icabod, that gives the same result.
coder247
@codere247: I misinterpreted your question. Now I've added a link to a site that should give you what you want.
Robusto
I'd be extremely careful with any code snippet that does browser detection
Álvaro G. Vicario
+1  A: 

I'd be careful resizing browser windows because it can very quickly get annoying (particularly if the user opens the page directly and not as a pop-up). What if a user wants a bit of space around the content to make it easier to read? In most browsers you can also turn off certain Javascript effects like moving and resizing windows - they may even be off by default.

icabod's idea of wrapping the content in a div should work fine at least for the height. If the width still shows the entire width of the current window then try adding float:left and it will fit to the width of the content.

A nice solution would be to use a lightbox script to display the content. I don't know of any off-hand that would resize to HTML/iframed content, but it's worth looking into.

DisgruntledGoat
this idea worked for me... but i added some values with the width and height. So now it's working for pages of all sizes... function windowResize() { var width= document.getElementById("resizeDiv").offsetWidth ; var height= document.getElementById("resizeDiv").offsetHeight ; alert(height); window.resizeTo(width+20,height+100); }
coder247
A: 

this idea worked for me... but i added some values with the width and height. So now it's working for pages of all sizes...

 function windowResize() {
       var width= document.getElementById("resizeDiv").offsetWidth ;
       var height= document.getElementById("resizeDiv").offsetHeight ;
       alert(height);
       window.resizeTo(width+20,height+100);
  }

'resizeDiv' is the div just inside the body. And a 'float:left' to the resizeDiv did the job for me.

coder247