hybrid
hybrid

Reputation: 3968

What's the raw JavaScript equivalent to jQuery's $(window).width

I've heard it's offset.width, document.documentElement.clientWidth, and window.innerWidth

I'm curious for projects which I cannot use jQuery on, which solution I should use?

Upvotes: 7

Views: 4967

Answers (3)

Šime Vidas
Šime Vidas

Reputation: 185883

This

window.innerWidth

The above property returns the same value as $( window ).width().

Live demo: http://jsfiddle.net/Jukh9/1/show/

However, IE8 does not implement this property...

Upvotes: 3

Alex Peattie
Alex Peattie

Reputation: 27637

function windowWidth() {
    var docElemProp = window.document.documentElement.clientWidth,
        body = window.document.body;
    return window.document.compatMode === "CSS1Compat" && docElemProp || body && body.clientWidth || docElemProp;
}

Taken (and modified slightly from the jQuery source:

https://github.com/jquery/jquery/blob/master/src/dimensions.js#L42

Upvotes: 7

DrStrangeLove
DrStrangeLove

Reputation: 11557

See for yourself. It uses different things. document.documentElement.clientWidth is among them.

It can also use document.body.clientWidth

Upvotes: 4

Related Questions