May 22, 2012

How can I get the client's browser height?

If you are a javascript programmer surely you've met the problem about calculating client's browser height (clientHeight) in different browser types.

1. What tells you the HTML specification (DHTML Object Model, HTML DOM)? The solution seems to be simple:
<script type="text/javascript">
  var iHeight = document.body.clientHeight;
  alert("The (inner) height of your browser is " + iHeight + "px");
</script>

2. But sometimes this solution can give you inappropriate result. The best way (what I use always) is the next:
<script type="text/javascript">
  var iHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
  alert("The (inner) height of your browser is " + iHeight + "px");
</script>

3. Using jQuery height() style property (or method):
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
  var iHeight = $(window).height();
  alert("The (inner) height of your browser is " + iHeight + "px");
</script>

No comments:

Post a Comment