JavaScript

window.innerWidth Vs. $(window).innerWidth()

What are the differences:

  • window.innerWidth: with scrollbar
  • $(window).innerWidth(): wrong usage
  • $(window).width(): without scrollbar
  • mediaquery: with scrollbar (at least the standard ones)

$(window).innerWidth(): this is actually a wrong way to get the inner width of window, because api.jquery.com/innerWidth states that “This method is not applicable to window and document objects; for these, use .width() instead.”

But what if we just need the inner width of window? We might need to adjust images according to width. In this case, use window.innerWidth.

window.innerWidth: quite literally, the width of window WITH scroll bar (as all mediaquery should behave). But sadly, IE8 doesn’t support it.

So use:

var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

To be clear, window.innerWidth is different from the latter two since only window.innerWidth includes scrollbar. But we don’t need to worry about getting the wrong width in IE8 because it doesn’t support Mediaquery–if it wants the width, it’ll have to resort to javascript solutions anyway.

Standard