2

I understand using @media queries in CSS, e.g. to apply rules when the browser's window is larger than a certain amount.

I understand that I can also use window.matchMedia() in Javascript to figure out if a particular query matches.

But how can I actually get the current values of the media that are being used?

e.g. If I wanted to access the values for media (e.g. screen, tv...), orientation, monochrome, device-width or width or other Media Features Are these accessible through the DOM somewhere?

artfulrobot
  • 20,637
  • 11
  • 55
  • 81

1 Answers1

1

As @abhitalks said in the comments, it's not possible to get these values from the DOM.

Here's my workaround.

For simple things with a small set of known values you can test those with window.matchMedia() one at a time.

For numeric things that support the min- prefix in a query, e.g. device-width you can do something like this:

var ls, l=0, h=8192, c=parseInt((l+h)/2), i=20;
while (i > 0 && (c - l >1) && (h - c>1)) {
  i--; // Shouldn't take more than 13 guesses, but in case of bugs!
  if (window.matchMedia('(min-device-width: ' + c + 'px)').matches) {
    l=c; ls=0;
  } else {
    h=c; ls=1;
  }
  c = parseInt((h+l)/2);
}
c -= ls;
alert("Device width is: ", c);

codepen demo

artfulrobot
  • 20,637
  • 11
  • 55
  • 81