11

I have a little problem with JavaScript, to get the screen width we use screen.width which returns the overall screen resolution, is there a command to get the resolution of the visible portion of the browser, like when the browser is not maximized?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
med
  • 227
  • 2
  • 3
  • 5

3 Answers3

32
function width(){
   return window.innerWidth 
       || document.documentElement.clientWidth 
       || document.body.clientWidth 
       || 0;
}

function height(){
   return window.innerHeight 
       || document.documentElement.clientHeight 
       || document.body.clientHeight 
       || 0;
}

Use them to return the height() or width() of the visible window.

JSFiddle example.

JCOC611
  • 19,111
  • 14
  • 69
  • 90
  • Thank you sir, window.innerWidth and window.innerHeight is what I want, it just works! but why all the other code? – med Feb 13 '11 at 22:30
  • 1
    @JCOC No need to write the window.innerWidth twice by using the ternary operator. Just use ||: `return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;` – Šime Vidas Feb 13 '11 at 22:36
  • In the original code I checked if `window.innerWidth` was a number, but I was too lazy to convert it from my framework to plain JS. – JCOC611 Feb 13 '11 at 22:37
  • Cleaner I guess, but it does exactly the same. – JCOC611 Feb 13 '11 at 22:54
1

I saw that the question was answered, but here is the code I used with an image to ilustrate.

function height(){
return(window.innerHeight)?
window.innerHeight:
document.documentElement.clientHeight||document.body.clientHeight||0;
}
$(document).ready(function(){
$('.first, .second').css('height',height());
});
$(window).resize(function() {
$('.first, .second').css('height',height());
});

JSFiddle Example

madaaah
  • 84
  • 5
1

The area you're describing is the viewport, and can typically be accessed by using window.innerWidth or window.innerHeight in modern browsers. IE6 is a bit different, but more information on handling the viewport width for all browsers can be found in this tutorial on obtaining viewport size.

NT3RP
  • 15,262
  • 9
  • 61
  • 97