Nov 12, 2012

Get page width dynamically with Javascript (or JQuery)

This quick script will display the current width of your browser window (useful for creating responsive web designs).

The HTML

Simply make a <div> element, which we will be used by JQuery to print out the window width:
<html>
  <body>
    <div id="dimensions">
      <span class="width"></span>
    </div>
  </body>
</html>

JQuery method

If you already use JQuery, then this is for you. If you aren't using it, you should consider it; it makes programming in Javascript a breeze!

To use this snippet, just download the JQuery library, link it into your page and add the following script:

<script>
  $("#dimensions .width").html($(window).width());
  $(window).resize(function(){
    $("#dimensions .width").html($(window).width());
  });

</script>

Javascript method

If you don't have JQuery this should work equally well:

<script>
  window.onresize = displayWindowSize;
  window.onload = displayWindowSize;
  function displayWindowSize() {
    // your size calculation code here
    document.getElementById("dimensions").innerHTML = myWidth + "x" + myHeight;
  };
</script>

Further reading

You can also browse my other content such as:

1 comment:

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!