Horay
Horay

Reputation: 1408

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

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.

Upvotes: 4

Views: 1587

Answers (2)

Andre Nel
Andre Nel

Reputation: 442

From your question it seems you are asking for the following (It is a trivial answer but I assume this is what you are asking):

var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;  

is equivalent to:

var width;
if (window.innerWidth > 0)
{
    width = window.innerWidth;
}
else
{
    width = screen.width;
}

or:

var width = screen.width;
if (window.innerWidth > 0)
{
    width = window.innerWidth;
}

they all do the same thing...

from your comment below you may want the following jsFiddle:
(which shows "window.innerWidth" is what you want (size of containing element) - but some browsers don't support it - so "screen.width" becomes the fallback which may not be correct as it is the width of the whole window and not just the containing element)

var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
$('#divOutput').html('The width is:' + width + 'px <br>' +
                     'window.innerWidth = ' + window.innerWidth + 'px & <br>' +
                     'screen.width = ' + screen.width + 'px');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="divOutput"></div>

if that doesn't help maybe look at:
window.innerWidth can't work on IE7. How to fix via JS and jQuery?

Upvotes: 1

kzettlmeier
kzettlmeier

Reputation: 83

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
  }
}

Upvotes: 7

Related Questions