I have the following HTML that displays a Square
. But if the page is zoomed past 100%, then the square goes away.
If the page is zoomed at 100% or below, then the square
will show.
Here is the code:
<div class="square"></div>
$(window).on("resize", function(e) {
$(".square").toggleClass("zoomed", window.devicePixelRatio > 1);
});
.square {
width: 190px;
height: 190px;
background: black;
}
.zoomed {
background: none;
}
The problem I am noticing is that, on mobile and on iPad devices , the square goes away and the zoomed
class is being added. I am not sure why it is getting zoomed on mobile and iPad even if I am not zooming it past 100%.
It should display the square on mobile and iPad. It should only get zoomed if the screen is set to more than 100%. Am I missing something in my code? It seems that when I am resizing the window, the square goes away and the Zoomed
class is added. How do I fix this problem? Or is there a different way to calculate zoom size?
2
Answers
The issue seems to be that on mobile devices and iPads, the default zoom level is greater than 100% already. So your code is detecting that default "zoomed" state and hiding the square automatically.
To fix this, you need to account for the default zoom level on those devices. You could check window.devicePixelRatio and see if it is greater than 2 or 3 perhaps before determining if the page is "zoomed".
For example js code:
This will only toggle the "zoomed" class if the pixel ratio exceeds 3x. So mobile/iPads at 2x will show the square by default.
You may need to tweak what threshold to use. But the key is accounting for the higher default device pixel ratios.
The
devicePixelRatio
property is not changing only when zooming the page. In case of retina display devices (such as ipads/macs), the screen itself has more physical pixels than the ones you display in your browser… therefore thedevicePixelRatio
is2
.Here’s a screenshot taken from the MDN page: