views:

1334

answers:

2

I am trying to write a javascript function to get the current browser width.

I found this one:

javascript:alert(document.body.offsetWidth);

But its problem that it fail if the body has width 100%

There is any other better function or a work around?

+14  A: 

It's a pain in the ass. I recommend skipping the nonsense and using jQuery, which lets you just do $(window).width().

chaos
If I recalled correctly, jQuery has pulled much of dimensions into the core. Do you still need dimensions to do what you're suggesting?
Nosredna
Turns out you don't. Which is awesome. Edited answer per. Thanks for the heads-up.
chaos
The $(window).width() support in jQuery is since version 1.2, in case it's relevant to anybody.
chaos
+6  A: 

The JavaScript property innerWidth can help you out in this case.

Geekpedia has a page about this: Get window width and height

From the article:

  function GetWidth()
  {
          var x = 0;
          if (self.innerHeight)
          {
                  x = self.innerWidth;
          }
          else if (document.documentElement && document.documentElement.clientHeight)
          {
                  x = document.documentElement.clientWidth;
          }
          else if (document.body)
          {
                  x = document.body.clientWidth;
          }
          return x;
  }

  function GetHeight()
  {
          var y = 0;
          if (self.innerHeight)
          {
                  y = self.innerHeight;
          }
          else if (document.documentElement && document.documentElement.clientHeight)
          {
                  y = document.documentElement.clientHeight;
          }
          else if (document.body)
          {
                  y = document.body.clientHeight;
          }
          return y;
  }
T Pops