Thursday, February 17, 2011

JavaScript: Available Window Height and Width

Ok, here is another junior varsity tip for using Javascript to get the true available window height and width. Note I stole this code from somewhere (though I tweaked it). I'd give credit if I remembered where I got it from, I don't.

function HSAvailWidth() {
  if (typeof window.innerWidth != 'undefined')
    return window.innerWidth;
  if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth !== 0)
    return document.documentElement.clientWidth;
  return document.getElementsByTagName('body')[0].clientWidth;
function HSAvailHeight() {
  if (typeof window.innerHeight != 'undefined')
    return window.innerHeight;
  if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientHeight != 'undefined' && document.documentElement.clientHeight !== 0)
    return document.documentElement.clientHeight;
  return document.getElementsByTagName('body')[0].clientHeight;

Or with jQuery...

$(window).height(); $(window).width();

Note: different browsers will have different available viewport height/widths because the browser tool bars very is size.

More here...


Anonymous said...

Thank you!

Shane Cherniss said...

Nice post.

Thanks for the information.