Sometimes, we may want to detect page zoom levels in modern browsers with JavaScript.
In this article, we’ll look at how to detect zoom levels in modern browsers with JavaScript.
Using the window.devicePixelRatio Property
One way to detect the browser zoom level is to use the window.devicePixelRatio
property.
For instance, we can write:
window.addEventListener('resize', () => {
const browserZoomLevel = Math.round(window.devicePixelRatio * 100);
console.log(browserZoomLevel)
})
When we zoom in or out, the resize
event will be triggered.
So we can listen to it with addEventListener
.
In the event handler callback, we get the window.devicePixelRatio
which has the ratio between the current pixel size and the regular pixel size.
Divide outerWidth by innerWidth
Since outerWidth
is measured in screen pixels and innerWidth
is measured in CSS pixels, we can use that to use the ratio between them to determine the zoom level.
For instance, we can write:
window.addEventListener('resize', () => {
const browserZoomLevel = (window.outerWidth - 8) / window.innerWidth;
console.log(browserZoomLevel)
})
Then browserZoomLevel
is proportional to how much we zoom in or out.
Conclusion
We can detect page zoom levels with the window.devicePixelRatio
property or the ratio between the outerWidth
and innerWidth
.