user2756503
user2756503

Reputation:

$(document).width() versus document.body.clientWidth

Are there any differences between these two declarations? I want to use one of them to fix some css issues on the mobile version of a responsive site. Some of the tutorials suggest the $(document).width(), while others the document.body.clientWidth. I know that the first one is jquery, and the second is plain JavaScript, but are there any differences besides that? Which one is better to use?

I'd like to use them this way:

if ($(document).width() < 768) { ... }

or

if (document.body.clientWidth < 768) { ... }

Upvotes: 4

Views: 6555

Answers (2)

mabeiyi
mabeiyi

Reputation: 367

document.body.clientWidth = $(document).width() + (left padding + right padding)

Upvotes: 1

Quentin
Quentin

Reputation: 943615

Yes, they are different. jQuery does a bunch of things to try to normalize the results.

See the source code:

if (elem.nodeType === 9) {
    doc = elem.documentElement;

    // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
    // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
    return Math.max(
    elem.body["scroll" + name], doc["scroll" + name], elem.body["offset" + name], doc["offset" + name], doc["client" + name]);
}

Upvotes: 1

Related Questions