1

on the following url:

https://gist.github.com/marcedwards/3446599

I found the following CSS code to check high DPI screens.

@media
    only screen and (-webkit-min-device-pixel-ratio: 1.3),
    only screen and (-o-min-device-pixel-ratio: 13/10),
    only screen and (min-resolution: 120dpi) {
    /* Your code to swap higher DPI images */

}

This code is based on:

https://bjango.com/articles/min-device-pixel-ratio/

My question is: Is there any way to create a flag (true/false) based on if above conditions are meet or not?

My goal is: I have a set of images: <img src="..." /> where depending on the screen resolution (above condition meets or not) I wanna use one image or other.

Thanks!

9
  • Are you asking if you can check device pixel ratio is above 1 or not using js? It is possible to set a flag in css and detect it with js. I would prefer you clarify exactly what you are after in what language first Commented Mar 29, 2018 at 15:05
  • I don't think this way would be the best way, but you could give the element for example opacity: 1 when that media query requirement is met. And check with javascript if the style of element a{ } equals opacity = 1 Commented Mar 29, 2018 at 15:07
  • window.devicePixelRatio Commented Mar 29, 2018 at 15:10
  • My goal is: I have a set of images: <img src="..." /> where depending on the screen resolution (above condition meets or not) I wanna use one image or other. Commented Mar 29, 2018 at 15:11
  • 3
    @davidesp I Imagine you want to use a bigger image for a dense screen so the image appears crystal clear, then you can use srcset on the image tag which requires no js developer.mozilla.org/en-US/docs/Learn/HTML/… Commented Mar 29, 2018 at 15:14

3 Answers 3

1

As @Huangism and @phuzi pointed out, the way is to use: srcset. The only caveat about this is it is not supported by IE yet (as of today).

Sign up to request clarification or add additional context in comments.

Comments

0

Could use some temporary element with a class to change on media query trigger to test:

HTML:

<p class="my-flag">Did the media query trigger?</p>

CSS:

@media
    only screen and (-webkit-min-device-pixel-ratio: 1.3),
    only screen and (-o-min-device-pixel-ratio: 13/10),
    only screen and (min-resolution: 120dpi) {
    /* Your code to swap higher DPI images */

.my-flag {
   color: red;
 }
}

And if you need this check in JS just ask

if($('.my-flag').style.color == "red")) {
     /* do stuff */ 
}

1 Comment

My goal is: I have a set of images: <img src="..." /> where depending on the screen resolution (above condition meets or not) I wanna use one image or other.
0

You can use window.matchMedia() for media queries in javascript.

if (window.matchMedia("(min-width:640px)").matches) {
    // mathes
} else {
    // not mathes
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.