This is a followup question to this quetsion: Get the device width in javascript.
What I'm trying to do, is get the equivalent css of @media (max-width: 600px) in JavaScript.
The accepted answer says to do the following:
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
Is that still correct? Will it work for all devices?
If it's correct, what's the point of checking (window.innerWidth > 0)?
I want to know if it still works. If you look at the last comment on the answer (with 6 upvotes) it says:
How does this have so many upvotes?
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;returns 667 on iphone 6 AND 6 Plus. This solution does not work correctly.
You should be able to do something like this:
if (matchMedia) {
  var mq = window.matchMedia("(max-width: 600px)");
  mq.addListener(WidthChange);
  WidthChange(mq);
}
function WidthChange(mq) {
  if (mq.matches) { 
     //Window width is less than or equal to 600px
  } else { 
     //Window width is greater than 600px
  }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With