How to get real window width

On 1-18-2005, in Coding, JavaScript, by Alex

Very useful function to get real browser’s width.
For height just replace [Width] to [Height]


	function getWindowWidth() {
		var windowWidth = 0;
		if (typeof(window.innerWidth) == 'number') {
			windowWidth = window.innerWidth;
		}
		else {
			if (document.documentElement && document.documentElement.clientWidth) {
				windowWidth = document.documentElement.clientWidth;
			}
			else {
				if (document.body && document.body.clientWidth) {
					windowWidth = document.body.clientWidth;
				}
			}
		}
		return windowWidth;
	}
 

16 Responses to How to get real window width

  1. Josh says:

    Thanks so much for this snippet, this was a life saver for a script I was working on. Great Job, Keep up the good work.

  2. Alex says:

    Welcome πŸ˜‰
    I am glad it was helpful

  3. Bjorn Larsen says:

    Thanks for that, made my day πŸ™‚

  4. chali says:

    Thanks for the function Alex πŸ™‚

  5. Alex says:

    Welcome πŸ™‚

  6. Rob Britton says:

    Awesome, very helpful. But why don’t you just go like this:
    function getWindowWidth() {
    return window.innerWidth || document.body.clientWidth;
    }

    This works great for me in IE6+, Firefox, Chrome…

  7. Alex says:

    @Rob: Thanks πŸ˜‰
    Well the post is 2005m, there was some other browsers set ;)))

  8. Aminiasi says:

    Well it works but it doesn’t actually give the real dimension(width or height) of a browser. Try resizing the browser window by reducing height or width and then refresh. It will give the current width and height of the resized window.

    So not actually what I was looking for!!

  9. Akhil says:

    thanks for the code

  10. Vincent says:

    Hi,

    I’ve combined this snippet with another to change css on the fly which allowing my then to publish my design for standards screens and HD’ screens.
    Another good one, thanks a lot dude!

    Vincent

  11. William says:

    dude, thank you so much. you save my day. May God bless U.

  12. Erundil says:

    Ok, but is it possible to use it as a parameter of table’s width?

    (Problem is: set table’s width to BrowserWidth-100px.

    How?)

    • Alex says:

      Actually it’s pretty easy but depends on your doctype. Also it could be 10 times easier if you use some js lib (I prefer jQuery). What about your models URL?

  13. Bastien says:

    Thansk a lot !!! Even if this script is from 2005, it still works perfectly.

    ..and for info I was getting wrong values with Jquery .width(), .height() (same with outerwidth(true) ) so this is still so damn useful !

  14. Paula says:

    Thanks, that save my day. πŸ™‚

  15. helpful one, thanks but how can I use it to be dynamic in the way of returning window.width changes when window.resize happens?