title: How do I find the virtual viewport/screen width using Javascript?
body: <p>Is there a consistent way to determine the width of the screen and virtual viewport for mobile devices using Javascript?  My target platforms are mobile Safari and Android's stock browser, but I'm also testing with other browsers on Android.</p>
  
  <p>I've tried with <code>screen.width</code>, <code>window.innerWidth</code>, <code>document.getElementByTagName("body")[0].clientWidth</code>, and jQuery's <code>$(window).width()</code>.</p>
  
  <p>Mobile Safari (from ios 3.1.3(7E18), original iPod touch) shows useful values, but the stock Android browser (Android 2.3.7) doesn't.</p>
  
  <p>Ideally, I think that screen.width should show the actual pixel resolution of the screen: 320px on the iPod Touch and 480px on the Samsung Galaxy S2.  Based on what I've been reading, one of the other numbers should show the width of the <i>layout</i> viewport which should be 980px on the iTouch and 800px on the Samsung Galaxy S2.
  .<br>
  .  </p>
  
  <h2>Code</h2>
  
  <pre><code>&lt;body&gt;
  &lt;h1&gt;screen.width: &lt;span id="screen_width"&gt;&lt;/span&gt;&lt;/h1&gt;
  &lt;h1&gt;window.innerwidth: &lt;span id="window_innerwidth"&gt;&lt;/span&gt;&lt;/h1&gt;
  &lt;h1&gt;clientWidth: &lt;span id="clientwidth"&gt;&lt;/span&gt;&lt;/h1&gt;
  &lt;h1&gt;jQuery width: &lt;span id="jquery_width"&gt;&lt;/span&gt;&lt;/h1&gt;
  &lt;/body&gt;
  
  &lt;script type="text/javascript" src="jquery/jquery-1.7.1.min.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;
      window.onload = function(){
          var swidth = screen.width;
          var wiwidth = window.innerWidth;
          var cwidth = document.getElementsByTagName("body")[0].clientWidth;
          var jwidth = $(window).width();
          document.getElementById("screen_width").innerHTML = swidth;
          document.getElementById("window_innerwidth").innerHTML = wiwidth;
          document.getElementById("clientwidth").innerHTML = cwidth;
          document.getElementById("jquery_width").innerHTML = jwidth;
      }
  &lt;/script&gt;
  </code></pre>
  
  <p>.<br>
  .  </p>
  
  <h2>Results</h2>
  
  <p><strong>iOS Safari</strong>:<br>
  screen.width: 320<br>
  window.innerwidth: 980<br>
  clientWidth: 964<br>
  jQuery width: 980  </p>
  
  <p><strong>Android Browser</strong>:<br>
  screen.width: 800<br>
  window.innerWidth: 800<br>
  clientWidth: 784<br>
  jQuery width: 800  </p>
  
  <p><strong>Firefox Mobile (a.k.a. Fennec)</strong>:<br>
  screen.width: 480<br>
  window.innerwidth: 980<br>
  clientWidth: 964<br>
  jQuery width: 980  </p>
  
  <p>The Safari results are certainly useable, but not the Android Browser's results.</p>
  
  <p>It's ironic that the Firefox mobile results are accurate.  Although it provides a nice browsing experience from a user perspective, it's not a big enough target for mobile devices and there are many other things that don't work well on this browser.</p>