javascript - Get the size of the screen, current web page and browser window

ID : 349

viewed : 141

Tags : javascripthtmljquerylayoutcross-browserjavascript

Top 5 Answer for javascript - Get the size of the screen, current web page and browser window

vote vote

90

You can get the size of the window or document with jQuery:

// Size of browser viewport. $(window).height(); $(window).width();  // Size of HTML document (same as pageHeight/pageWidth in screenshot). $(document).height(); $(document).width(); 

For screen size you can use the screen object:

window.screen.height; window.screen.width; 
vote vote

85

This has everything you need to know: Get viewport/window size

but in short:

var win = window,     doc = document,     docElem = doc.documentElement,     body = doc.getElementsByTagName('body')[0],     x = win.innerWidth || docElem.clientWidth || body.clientWidth,     y = win.innerHeight|| docElem.clientHeight|| body.clientHeight; alert(x + ' × ' + y); 

Fiddle

Please stop editing this answer. It's been edited 22 times now by different people to match their code format preference. It's also been pointed out that this isn't required if you only want to target modern browsers - if so you only need the following:

const width  = window.innerWidth || document.documentElement.clientWidth ||  document.body.clientWidth; const height = window.innerHeight|| document.documentElement.clientHeight||  document.body.clientHeight;  console.log(width, height); 
vote vote

79

Here is a cross browser solution with pure JavaScript (Source):

var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;  var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; 
vote vote

64

A non-jQuery way to get the available screen dimension. window.screen.width/height has already been put up, but for responsive webdesign and completeness sake I think its worth to mention those attributes:

alert(window.screen.availWidth); alert(window.screen.availHeight); 

http://www.quirksmode.org/dom/w3c_cssom.html#t10 :

availWidth and availHeight - The available width and height on the screen (excluding OS taskbars and such).

vote vote

58

But when we talk about responsive screens and if we want to handle it using jQuery for some reason,

window.innerWidth, window.innerHeight 

gives the correct measurement. Even it removes the scroll-bar's extra space and we don't need to worry about adjusting that space :)

Top 3 video Explaining javascript - Get the size of the screen, current web page and browser window

Related QUESTION?