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;
	}
 

13 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. 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…

  6. Alex says:

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

  7. 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!!

  8. Akhil says:

    thanks for the code

  9. 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

  10. William says:

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

  11. 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?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>