Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get css equivalent of "max-width: 600px" using JavaScript

Tags:

javascript

css

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.

like image 624
Horay Avatar asked Sep 17 '25 03:09

Horay


1 Answers

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
  }
}
like image 53
kzettlmeier Avatar answered Sep 19 '25 17:09

kzettlmeier